Example usage for javax.swing JOptionPane QUESTION_MESSAGE

List of usage examples for javax.swing JOptionPane QUESTION_MESSAGE

Introduction

In this page you can find the example usage for javax.swing JOptionPane QUESTION_MESSAGE.

Prototype

int QUESTION_MESSAGE

To view the source code for javax.swing JOptionPane QUESTION_MESSAGE.

Click Source Link

Document

Used for questions.

Usage

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

/**
 * @param databaseName/*from w  ww .  ja va2s. co  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:edu.ku.brc.specify.datamodel.busrules.BaseTreeBusRules.java

/**
 * @param parentDataObj/*  w w  w .j  av a2s . c om*/
 * @param dataObj
 * @param isExistingObject
 * @return
 */
@SuppressWarnings("unchecked")
public STATUS checkForSiblingWithSameName(final Object parentDataObj, final Object dataObj,
        final boolean isExistingObject) {
    STATUS result = STATUS.OK;
    if (parentHasChildWithSameName(parentDataObj, dataObj)) {
        String parentName;
        if (parentDataObj == null) {
            parentName = ((Treeable<T, D, I>) dataObj).getParent().getFullName();
        } else {
            parentName = ((Treeable<T, D, I>) parentDataObj).getFullName();
        }
        boolean saveIt = UIRegistry.displayConfirm(
                UIRegistry.getResourceString("BaseTreeBusRules.IDENTICALLY_NAMED_SIBLING_TITLE"),
                String.format(UIRegistry.getResourceString("BaseTreeBusRules.IDENTICALLY_NAMED_SIBLING_MSG"),
                        parentName, ((Treeable<T, D, I>) dataObj).getName()),
                UIRegistry.getResourceString("SAVE"), UIRegistry.getResourceString("CANCEL"),
                JOptionPane.QUESTION_MESSAGE);
        if (!saveIt) {
            //Adding to reasonList prevents blank "Issue of Concern" popup -
            //but causes annoying second "duplicate child" nag.
            reasonList.add(UIRegistry.getResourceString("BaseTreeBusRules.IDENTICALLY_NAMED_SIBLING")); // XXX
            // i18n
            result = STATUS.Error;
        }
    }
    return result;
}

From source file:edu.ku.brc.af.ui.db.DatabaseLoginPanel.java

/**
 * @param clsName/*from w  w  w . j av  a2 s  .  c  om*/
 */
private void doLoginContinuing(final String clsName) {
    final SwingWorker worker = new SwingWorker() {
        long eTime;
        boolean isLoggedIn = false;
        boolean timeOK = false;
        boolean isLoginCancelled = false;
        boolean isLoginFailed = false;

        Pair<String, String> usrPwd = null;

        @Override
        public Object construct() {
            if (UIRegistry.isMobile()) {
                File mobileTmpDir = DBConnection.getMobileMachineDir(getDatabaseName());
                if (mobileTmpDir == null) {
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifyDBSetupWizard.class,
                            new RuntimeException("Couldn't get MobileTempDir"));
                }

                if (mobileTmpDir != null) {
                    UIRegistry.setEmbeddedDBPath(mobileTmpDir.getAbsolutePath());
                }
                //log.debug(UIRegistry.getEmbeddedDBPath());

                if (UIRegistry.getMobileEmbeddedDBPath() == null) {
                    UIRegistry.setMobileEmbeddedDBPath(
                            UIRegistry.getDefaultMobileEmbeddedDBPath(getDatabaseName()));
                    //log.debug(UIRegistry.getMobileEmbeddedDBPath());
                }
            }

            String connStr = getConnectionStr();

            DBConnection.checkForEmbeddedDir(connStr);

            UIRegistry.dumpPaths();

            eTime = System.currentTimeMillis();

            usrPwd = getMasterUsrPwd();
            if (usrPwd != null) {
                isLoggedIn = UIHelper.tryLogin(getDriverClassName(), getDialectClassName(), getDatabaseName(),
                        getConnectionStr(), usrPwd.first, usrPwd.second);
                if (isLoggedIn && masterUsrPwdProvider != null) {
                    isLoggedIn &= jaasLogin();
                }
            } else if (usrPwd == null) {
                isLoginCancelled = true;
                isLoginFailed = true;
                return null;
            }

            if (isLoggedIn) {
                if (StringUtils.isNotEmpty(appName)) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            //Not exactly true yet, but make sure users know that this is NOT Specify starting up. 
                            setMessage(String.format(getResourceString("Starting"), appName), false); //$NON-NLS-1$
                        }
                    });
                }

                DatabaseDriverInfo drvInfo = dbDrivers.get(dbDriverCBX.getSelectedIndex());
                if (drvInfo != null) {
                    if (!DBConnection.getInstance().isEmbedded() && !UIRegistry.isMobile()) {
                        drvInfo.setPort((Integer) portSpinner.getValue());
                    }

                    DBConnection.getInstance().setDbCloseConnectionStr(drvInfo.getConnectionStr(
                            DatabaseDriverInfo.ConnectionType.Close, getServerName(), getDatabaseName()));
                    DBConnection.getInstance().setServerName(getServerName());
                    DBConnection.getInstance()
                            .setDriverName(((DatabaseDriverInfo) dbDriverCBX.getSelectedItem()).getName());
                    DBConnection.getInstance().setConnectionStr(drvInfo.getConnectionStr(
                            DatabaseDriverInfo.ConnectionType.Open, getServerName(), getDatabaseName()));

                    //Assuming a single institution
                    List<Object[]> relmanage = BasicSQLUtils
                            .query("select IsReleaseManagedGlobally from institution");
                    if (relmanage.size() > 1 /*which means someone has been hacking*/) {
                        log.warn(
                                "There is more than one institution defined. IsReleaseManagedGlobally was read from first available institution record.");
                    }
                    Boolean isReleaseManagedGlobally = null;
                    if (relmanage.size() > 0 /*one would hope*/) {
                        isReleaseManagedGlobally = (Boolean) relmanage.get(0)[0];
                    }
                    AppPreferences localPrefs = AppPreferences.getLocalPrefs();
                    String VERSION_CHECK = "version_check.auto";
                    boolean localChk4VersionUpdate = localPrefs.getBoolean(VERSION_CHECK, true);
                    //UIRegistry.displayInfoMsgDlg("doLoginContinuing(): isReleasedManagedGlobally=" + isReleaseManagedGlobally + ", local update pref=" + localChk4VersionUpdate);
                    if ((isReleaseManagedGlobally == null || !isReleaseManagedGlobally)
                            && localChk4VersionUpdate) {
                        try {
                            com.install4j.api.launcher.SplashScreen.hide();
                            ApplicationLauncher.Callback callback = new ApplicationLauncher.Callback() {
                                @Override
                                public void exited(int exitValue) {
                                    //System.out.println("ExitValue: " + exitValue);
                                    if (exitValue == 0) {
                                        System.exit(0);
                                    } else {
                                        doLoginContinuing2();
                                    }
                                }

                                @Override
                                public void prepareShutdown() {
                                    //System.out.println("prepareShutdown(): exiting");
                                    System.exit(0);
                                }
                            };
                            //UIRegistry.displayInfoMsgDlg("doLoginContinuing(): launching update application, proxy settings: " + Specify.getProxySettings());
                            ApplicationLauncher.launchApplication("100", Specify.getProxySettings(), true,
                                    callback);
                        } catch (Exception ex) {
                            log.error(ex);
                            doLoginContinuing2();
                        }
                    } else {
                        doLoginContinuing2();
                    }
                }
            }
            return null;
        }

        public void doLoginContinuing2() {
            if (shouldCheckForSchemaUpdate) {
                // This needs to be done before Hibernate starts up
                SchemaUpdateService.getInstance().setAppCanUpdateSchema(appCanUpdateSchema);
                SchemaUpdateType status = SchemaUpdateService.getInstance()
                        .updateSchema(UIRegistry.getAppVersion(), getUserName());
                if (status == SchemaUpdateType.Error) {
                    StringBuilder sb = new StringBuilder();
                    for (String s : SchemaUpdateService.getInstance().getErrMsgList()) {
                        sb.append(s);
                        sb.append("\n");
                    }
                    sb.append(getResourceString("APP_EXIT")); // 18N
                    UIRegistry.showError(sb.toString());
                    if (!appCanUpdateSchema) {
                        isLoginCancelled = true; //works when the app is not the main specify app
                        isLoggedIn = false; //so as not to have to meddle with SwingWorker finished() method
                    }
                    CommandDispatcher.dispatch(new CommandAction("App", "AppReqExit", null));

                } else if (status == SchemaUpdateType.Success || status == SchemaUpdateType.SuccessAppVer) {
                    String arg = status == SchemaUpdateType.SuccessAppVer ? UIRegistry.getAppVersion() : "";
                    UIRegistry.showLocalizedMsg(JOptionPane.QUESTION_MESSAGE, "INFORMATION",
                            status == SchemaUpdateType.SuccessAppVer ? "APPVER_UP_OK" : "SCHEMA_UP_OK", arg);
                }
            }

        }

        // Runs on the event-dispatching thread.
        @Override
        public void finished() {
            statusBar.setIndeterminate(clsName, false);

            // I am not sure this is the rightplace for this
            // but this is where I am putting it for now
            if (isLoggedIn) {
                setMessage(getResourceString("LoadingSchema"), false); //$NON-NLS-1$
                statusBar.repaint();

                // Note: this doesn't happen on the GUI thread
                DataProviderFactory.getInstance().shutdown();

                // This restarts the System
                DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession();
                session.close();

                long endTime = System.currentTimeMillis();
                eTime = (endTime - eTime) / 1000;
                timeOK = true;

                if (progressWorker != null) {
                    progressWorker.stop();
                }

                statusBar.setProgressDone(getClass().getName());

                if (timeOK) {
                    elapsedTime = eTime;
                    loginAccumTime += elapsedTime;

                    if (loginCount < 1000) {
                        String basePrefNameStr = getDatabaseName() + "." + getUserName() + "."; //$NON-NLS-1$ //$NON-NLS-2$
                        AppPreferences.getLocalPrefs().putLong(basePrefNameStr + "logincount", ++loginCount);//$NON-NLS-1$
                        AppPreferences.getLocalPrefs().putLong(basePrefNameStr + "loginaccumtime", //$NON-NLS-1$
                                loginAccumTime);

                    }
                }

                loginOK();

                isLoggingIn = false;

            } else {
                if (!isLoginCancelled) {
                    String msg = DBConnection.getInstance().getErrorMsg();
                    setMessage(StringUtils.isEmpty(msg) ? getResourceString("INVALID_LOGIN") : msg, true);

                    if (DBConnection.getInstance().isEmbedded() || UIRegistry.isMobile()) {
                        DataProviderFactory.getInstance().shutdown();
                        DBConnection.shutdown();
                        DBConnection.shutdownFinalConnection(false, true);
                        DBConnection.startOver();

                    } else if (usrPwd != null) {
                        doCheckPermissions(usrPwd);
                    }
                } else if (!isLoginFailed) {
                    if (dbListener != null) {
                        dbListener.cancelled();
                    }
                }

                enableUI(true);
                isLoggingIn = false;
            }

            if (isAutoClose) {
                updateUIControls();
            }

        }
    };
    worker.start();
}

From source file:convcao.com.caoAgent.convcaoNeptusInteraction.java

@Override
public void initSubPanel() {

    jPanelMain = new javax.swing.JPanel();
    jPanel1 = new javax.swing.JPanel();
    jPanel2 = new javax.swing.JPanel();
    jLabel2 = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextPane1 = new javax.swing.JTextPane();
    renewButton = new javax.swing.JButton();
    jLabel4 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jLabel5 = new javax.swing.JLabel();
    jPasswordField1 = new javax.swing.JPasswordField();
    connectButton = new javax.swing.JButton();
    jScrollPane2 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jLabel7 = new javax.swing.JLabel();
    jLabel8 = new javax.swing.JLabel();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    jLabel9 = new javax.swing.JLabel();
    jLabel10 = new javax.swing.JLabel();
    jLabel11 = new javax.swing.JLabel();
    jLabel12 = new javax.swing.JLabel();
    jLabel6 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();

    jLabel11.setIcon(noptilusLogo);//from w ww .  ja  v  a2 s.  co  m

    jLabel12.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
    jLabel12.setText("<html>www.convcao.com<br>version 0.01</html>");
    jLabel12.setToolTipText("");
    jLabel12.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(jPanel1Layout
            .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel11, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                    Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                    jPanel1Layout.createSequentialGroup().addGap(0, 19, Short.MAX_VALUE).addComponent(jLabel12,
                            javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                            javax.swing.GroupLayout.PREFERRED_SIZE)));
    jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 45,
                            javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE,
                            javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 0, Short.MAX_VALUE)));

    jLabel2.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
    jLabel2.setText("Unique ID");

    jTextPane1.setEditable(true);
    jScrollPane1.setViewportView(jTextPane1);
    //jTextPane1.getAccessibleContext().setAccessibleName("");

    renewButton.setText("RENEW");
    renewButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            renewButtonActionPerformed(evt);
        }
    });

    jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
    jLabel4.setText("Username");

    jTextField1.setText("FTPUser");

    jLabel5.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
    jLabel5.setText("Password");

    jPasswordField1.setText("FTPUser123");

    connectButton.setText("Connect");
    connectButton.setEnabled(false);
    connectButton.setActionCommand("connect");
    connectButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            try {
                connectButtonActionPerformed(evt);
            } catch (FileNotFoundException | UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SocketException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

    jTextArea1.setEditable(false);
    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane2.setViewportView(jTextArea1);

    jLabel7.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
    jLabel7.setText("Command Monitor");

    jButton1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
    jButton1.setText("START");
    jButton1.setEnabled(false);
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            StartButtonActionPerformed(evt);
        }
    });

    jButton2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
    jButton2.setText("STOP");
    jButton2.setEnabled(false);
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            StopButtonActionPerformed(evt);
        }
    });

    jLabel1.setForeground(new java.awt.Color(255, 0, 0));
    jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel1.setText(
            "<html>Click HERE to activate the web service using your ID<br>When the web application is ready, press Start </html>");
    jLabel1.setCursor(new Cursor(Cursor.HAND_CURSOR));
    jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            try {
                jLabel1MouseClicked(evt);
            } catch (URISyntaxException | IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

    //jLabel9.setText("Working...");
    jLabel9.setIcon(runIcon);
    jLabel9.setVisible(false);

    jLabel10.setText("---");

    jLabel6.setForeground(new java.awt.Color(0, 204, 0));
    jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel6.setText("---");

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(jPanel2Layout
            .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel2Layout.createSequentialGroup().addContainerGap().addComponent(
                                    jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE,
                                    javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING,
                                    jPanel2Layout.createSequentialGroup().addGroup(jPanel2Layout
                                            .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(jPanel2Layout.createSequentialGroup()
                                                    .addGap(126, 126, 126).addComponent(jLabel7,
                                                            javax.swing.GroupLayout.PREFERRED_SIZE, 110,
                                                            javax.swing.GroupLayout.PREFERRED_SIZE))
                                            .addGroup(jPanel2Layout.createSequentialGroup().addGap(23, 23, 23)
                                                    .addGroup(jPanel2Layout
                                                            .createParallelGroup(
                                                                    javax.swing.GroupLayout.Alignment.TRAILING)
                                                            .addGroup(jPanel2Layout.createParallelGroup(
                                                                    javax.swing.GroupLayout.Alignment.LEADING,
                                                                    false)
                                                                    .addGroup(
                                                                            javax.swing.GroupLayout.Alignment.TRAILING,
                                                                            jPanel2Layout
                                                                                    .createSequentialGroup()
                                                                                    .addComponent(jLabel9,
                                                                                            javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                            56,
                                                                                            javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                                    .addPreferredGap(
                                                                                            javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                                                                            javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                                            Short.MAX_VALUE)
                                                                                    .addComponent(jButton1,
                                                                                            javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                            80,
                                                                                            javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                                    .addGap(29, 29, 29)
                                                                                    .addComponent(jButton2,
                                                                                            javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                            77,
                                                                                            javax.swing.GroupLayout.PREFERRED_SIZE))
                                                                    .addComponent(jScrollPane2,
                                                                            javax.swing.GroupLayout.Alignment.TRAILING,
                                                                            javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                            308,
                                                                            javax.swing.GroupLayout.PREFERRED_SIZE))
                                                            .addComponent(jLabel10,
                                                                    javax.swing.GroupLayout.Alignment.LEADING,
                                                                    javax.swing.GroupLayout.PREFERRED_SIZE, 103,
                                                                    javax.swing.GroupLayout.PREFERRED_SIZE)
                                                            .addComponent(jLabel1,
                                                                    javax.swing.GroupLayout.PREFERRED_SIZE, 299,
                                                                    javax.swing.GroupLayout.PREFERRED_SIZE))))
                                            .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(jPanel2Layout.createSequentialGroup().addGap(0, 0, Short.MAX_VALUE)
                                    .addGroup(jPanel2Layout
                                            .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                                                    jPanel2Layout.createSequentialGroup()
                                                            .addComponent(jLabel2,
                                                                    javax.swing.GroupLayout.PREFERRED_SIZE, 80,
                                                                    javax.swing.GroupLayout.PREFERRED_SIZE)
                                                            .addGap(18, 18, 18)
                                                            .addComponent(jScrollPane1,
                                                                    javax.swing.GroupLayout.PREFERRED_SIZE, 130,
                                                                    javax.swing.GroupLayout.PREFERRED_SIZE)
                                                            .addGap(18, 18, 18).addComponent(renewButton))
                                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                                                    jPanel2Layout.createSequentialGroup().addGroup(jPanel2Layout
                                                            .createParallelGroup(
                                                                    javax.swing.GroupLayout.Alignment.LEADING,
                                                                    false)
                                                            .addGroup(jPanel2Layout.createSequentialGroup()
                                                                    .addComponent(jLabel4,
                                                                            javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                            64,
                                                                            javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                    .addGap(18, 18, 18)
                                                                    .addComponent(jTextField1,
                                                                            javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                            130,
                                                                            javax.swing.GroupLayout.PREFERRED_SIZE))
                                                            .addGroup(jPanel2Layout.createSequentialGroup()
                                                                    .addComponent(jLabel5,
                                                                            javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                            64,
                                                                            javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                    .addGap(18, 18, 18)
                                                                    .addComponent(jPasswordField1)))
                                                            .addGap(14, 14, 14).addComponent(connectButton)))))
                    .addContainerGap()));
    jPanel2Layout
            .setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                            .addGroup(jPanel2Layout
                                    .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(renewButton, javax.swing.GroupLayout.DEFAULT_SIZE,
                                            javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jScrollPane1).addComponent(jLabel2,
                                            javax.swing.GroupLayout.PREFERRED_SIZE, 25,
                                            javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGap(18, 18, 18)
                            .addGroup(jPanel2Layout
                                    .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE,
                                            javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,
                                            javax.swing.GroupLayout.DEFAULT_SIZE,
                                            javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(jPanel2Layout
                                    .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE,
                                            javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE,
                                            javax.swing.GroupLayout.DEFAULT_SIZE,
                                            javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(connectButton, javax.swing.GroupLayout.DEFAULT_SIZE,
                                            javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 21,
                                    javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jLabel1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 20,
                                    javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 113,
                                    javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(jPanel2Layout
                                    .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE,
                                            javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE,
                                            javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 33,
                                            javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 26,
                                    javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(5, 5, 5)));

    jLabel1.getAccessibleContext().setAccessibleName("jLabel1");

    jLabel3.setFont(new java.awt.Font("Tahoma", 1, 22)); // NOI18N
    jLabel3.setText("Real Time Navigation");

    jLabel8.setIcon(appLogo);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(jPanelMain);
    jPanelMain.setLayout(layout);
    layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jLabel3)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
                                    javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE,
                                    javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jPanel2,
                            javax.swing.GroupLayout.PREFERRED_SIZE, 331, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap()));
    layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup().addComponent(jLabel3)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 110,
                                            javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
                                            javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE,
                                    javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addContainerGap()));

    addMenuItem("Settings>Noptilus>Coordinate Settings",
            ImageUtils.getIcon(PluginUtils.getPluginIcon(getClass())), new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    PluginUtils.editPluginProperties(coords, true);
                    coords.saveProps();
                }
            });

    addMenuItem("Settings>Noptilus>ConvCAO Settings", ImageUtils.getIcon(PluginUtils.getPluginIcon(getClass())),
            new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    PluginUtils.editPluginProperties(convcaoNeptusInteraction.this, true);
                }
            });

    addMenuItem("Settings>Noptilus>Force vehicle depth",
            ImageUtils.getIcon(PluginUtils.getPluginIcon(getClass())), new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (positions.isEmpty()) {
                        GuiUtils.errorMessage(getConsole(), "Force vehicle depth",
                                "ConvCAO control is not active");
                        return;
                    }
                    String[] choices = nameTable.values().toArray(new String[0]);

                    String vehicle = (String) JOptionPane.showInputDialog(getConsole(), "Force vehicle depth",
                            "Choose vehicle", JOptionPane.QUESTION_MESSAGE, null, choices, choices[0]);

                    if (vehicle != null) {
                        double depth = depths.get(vehicle);
                        String newDepth = JOptionPane.showInputDialog(getConsole(), "New depth", "" + depth);
                        try {
                            double dd = Double.parseDouble(newDepth);
                            depths.put(vehicle, dd);
                        } catch (Exception ex) {
                            GuiUtils.errorMessage(getConsole(), ex);
                        }
                    }
                }
            });

    add(jPanelMain);

    renewButtonActionPerformed(null);

}

From source file:generadorqr.jifrGestionArticulos.java

private void btnEliminarArticulosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnEliminarArticulosMouseClicked
    // TODO add your handling code here:
    Object[] opciones = { "Aceptar", "Cancelar" };
    if (!idA.isEmpty()) {
        int eleccion = JOptionPane.showOptionDialog(this, "Est seguro que desea eliminar", "Eliminar",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, opciones, "Aceptar");
        if (eleccion == JOptionPane.YES_OPTION)
            EliminarArticulos();//  ww  w . j av  a  2s. co  m
    } else
        JOptionPane.showMessageDialog(this, "No ha seleccionado un registro a eliminar");
}

From source file:edu.ku.brc.af.ui.forms.TableViewObj.java

/**
 * Deletes a Row in the table and there an data object
 * @param rowIndex the item to be deleted
 *///  ww w  .  j av  a 2  s. c o m
protected void deleteRow(final int rowIndex) {
    FormDataObjIFace dObj = (FormDataObjIFace) dataObjList.get(rowIndex);
    if (dObj != null) {
        Object[] delBtnLabels = { getResourceString(addSearch ? "Remove" : "Delete"),
                getResourceString("CANCEL") };
        int rv = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(),
                UIRegistry.getLocalizedMessage(addSearch ? "ASK_REMOVE" : "ASK_DELETE",
                        dObj.getIdentityTitle()),
                getResourceString(addSearch ? "Remove" : "Delete"), JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE, null, delBtnLabels, delBtnLabels[1]);
        if (rv == JOptionPane.YES_OPTION) {
            boolean doOtherSide = true;

            DBTableInfo parentTblInfo = DBTableIdMgr.getInstance()
                    .getByShortClassName(parentDataObj.getClass().getSimpleName());
            if (parentTblInfo != null) {
                DBTableChildIFace ci = parentTblInfo.getItemByName(cellName);
                if (ci instanceof DBRelationshipInfo) {
                    DBRelationshipInfo ri = (DBRelationshipInfo) ci;
                    doOtherSide = ri.getType() == DBRelationshipInfo.RelationshipType.OneToMany;
                    log.debug(ri.getType());
                }
            }
            doOtherSide = false;
            parentDataObj.removeReference(dObj, dataSetFieldName, doOtherSide || addSearch);
            if (addSearch && mvParent != null && dObj.getId() != null) {
                mvParent.getTopLevel().addToBeSavedItem(dObj);
            }

            // 'addSearch' is used in FormViewObj, but here maybe we need to use 'doOtherSide'
            if (addSearch && mvParent != null && dObj.getId() != null) {
                mvParent.getTopLevel().addToBeSavedItem(dObj);
            }

            dataObjList.remove(rowIndex);

            model.fireDataChanged();
            table.invalidate();

            JComponent comp = mvParent.getTopLevel();
            comp.validate();
            comp.repaint();

            reorderItems(rowIndex);

            tellMultiViewOfChange();

            table.getSelectionModel().clearSelection();
            updateUI(false);

            mvParent.getTopLevel().getCurrentValidator().setHasChanged(true);
            mvParent.getTopLevel().getCurrentValidator().validateForm();

            mvParent.getCurrentValidator().setHasChanged(true);
            mvParent.getMultiViewParent().getCurrentValidator().validateForm();

            if (!addSearch) {
                // Delete a child object by caching it in the Top Level MultiView
                if (mvParent != null && !mvParent.isTopLevel()) {
                    mvParent.getTopLevel().addDeletedItem(dObj);
                    String delMsg = (businessRules != null) ? businessRules.getDeleteMsg(dObj) : "";
                    UIRegistry.getStatusBar().setText(delMsg);
                }
            }
        }
    }
}

From source file:eu.apenet.dpt.standalone.gui.DataPreparationToolGUI.java

private boolean isCorrect(File file) {
    if (fileInstances.containsKey(file.getName())) {
        if (JOptionPane.showConfirmDialog(getContentPane(),
                labels.getString("error.file.exists") + " - " + labels.getString("error.file.exists.overwrite"),
                labels.getString("options.howLoadNewFiles"), JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
            ((ProfileListModel) getXmlEadList().getModel()).removeFile(file);
        }/* ww w.  j av  a  2  s  . co m*/
    }
    if (checkLoadingFiles() && XmlChecker.isXmlParseable(file) != null) {
        createErrorOrWarningPanel(new Exception(labels.getString("error.file.notXml")), false,
                labels.getString("error.file.notXml"), this);
    }
    return !fileInstances.containsKey(file.getName()) && !file.isDirectory()
            && (!checkLoadingFiles() || checkLoadingFiles() && XmlChecker.isXmlParseable(file) == null);
}

From source file:com.archivas.clienttools.arcmover.gui.panels.ProfilePanel.java

public final void renameSelectedRow() {
    try {/*w  ww  . jav  a2 s .  c o  m*/
        if (getSelectedRowCount() != 1) {
            JOptionPane.showMessageDialog(this, "You may only rename one object at a time", "",
                    JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        // show rename dialog
        String newFileName;
        String oldFileName = selectedFile.getFileName();

        // The slugs are stand-ins for file type in messages
        final String lSlug = (selectedFile.isDirectory() ? "directory" : "file");
        final String uSlug = (selectedFile.isDirectory() ? "Directory" : "File");

        do {
            final String message = String.format("New %s name", lSlug);
            final String title = String.format("Rename %s", uSlug);

            // get new file name from user
            newFileName = (String) JOptionPane.showInputDialog(this.getParent(), message, title,
                    JOptionPane.QUESTION_MESSAGE, null, null, selectedFile.getFileName());

            // check if user pressed 'cancel' button
            if (newFileName == null) {
                LOG.info("Rename operation canceled");

                return;
            }

            // validate the new file name
            // TODO: Complete validation based on target OS is not performed at this time. If
            // needed, that should be added here.
            if (newFileName.contains("/") || newFileName.contains("\\")) {
                final String errorMessage = String.format("Invalid %s name", lSlug);
                JOptionPane.showMessageDialog(this.getParent(), errorMessage, "Rename",
                        JOptionPane.WARNING_MESSAGE);
                newFileName = null;
            }

        } while ((newFileName == null) || (newFileName.length() <= 0));

        try {
            boolean success;
            success = arcMoverEngine.renameTo(profileModel.getSelectedProfile(),
                    selectedFile.getParent().getPath(), oldFileName, newFileName);
            if (!success) {
                throw new IOException(String.format("Could not rename %s.", lSlug));
            }
            LOG.info("Renamed " + oldFileName + " to " + newFileName);

            HCPDataMigrator.getInstance().refreshMatchingPanels(profileModel.getSelectedProfile(), currentDir);

        } catch (Exception e1) {
            String uiErrorMsg;
            String logErrorMsg;

            logErrorMsg = "Could not rename " + selectedFile.getPath() + " to " + newFileName;
            uiErrorMsg = DBUtils.getErrorMessage("Error renaming " + selectedFile.getPath(), e1);
            LOG.log(Level.WARNING, logErrorMsg, e1);
            GUIHelper.showMessageDialog(this.getParent(), uiErrorMsg, "Rename", JOptionPane.ERROR_MESSAGE);
        }
    } catch (RuntimeException e1) {
        // TODO: Implement Proper Error Handling
        LOG.log(Level.WARNING, "Unexpected Exception", e1);
        throw e1;
    }
}

From source file:net.sf.jabref.gui.BasePanel.java

private boolean saveDatabase(File file, boolean selectedOnly, Charset enc,
        SavePreferences.DatabaseSaveType saveType) throws SaveException {
    SaveSession session;/*from  www .j a  va2s  .c  o m*/
    frame.block();
    final String SAVE_DATABASE = Localization.lang("Save database");
    try {
        SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs).withEncoding(enc)
                .withSaveType(saveType);
        BibtexDatabaseWriter databaseWriter = new BibtexDatabaseWriter(FileSaveSession::new);
        if (selectedOnly) {
            session = databaseWriter.savePartOfDatabase(bibDatabaseContext, mainTable.getSelectedEntries(),
                    prefs);
        } else {
            session = databaseWriter.saveDatabase(bibDatabaseContext, prefs);
        }

        registerUndoableChanges(session);

    } catch (UnsupportedCharsetException ex2) {
        JOptionPane.showMessageDialog(frame,
                Localization.lang("Could not save file.") + ' '
                        + Localization.lang("Character encoding '%0' is not supported.", enc.displayName()),
                SAVE_DATABASE, JOptionPane.ERROR_MESSAGE);
        throw new SaveException("rt");
    } catch (SaveException ex) {
        if (ex.specificEntry()) {
            // Error occurred during processing of
            // be. Highlight it:
            final int row = mainTable.findEntry(ex.getEntry());
            final int topShow = Math.max(0, row - 3);
            mainTable.setRowSelectionInterval(row, row);
            mainTable.scrollTo(topShow);
            showEntry(ex.getEntry());
        } else {
            LOGGER.warn("Could not save", ex);
        }

        JOptionPane.showMessageDialog(frame, Localization.lang("Could not save file.") + "\n" + ex.getMessage(),
                SAVE_DATABASE, JOptionPane.ERROR_MESSAGE);
        throw new SaveException("rt");

    } finally {
        frame.unblock();
    }

    boolean commit = true;
    if (!session.getWriter().couldEncodeAll()) {
        FormBuilder builder = FormBuilder.create()
                .layout(new FormLayout("left:pref, 4dlu, fill:pref", "pref, 4dlu, pref"));
        JTextArea ta = new JTextArea(session.getWriter().getProblemCharacters());
        ta.setEditable(false);
        builder.add(Localization.lang("The chosen encoding '%0' could not encode the following characters:",
                session.getEncoding().displayName())).xy(1, 1);
        builder.add(ta).xy(3, 1);
        builder.add(Localization.lang("What do you want to do?")).xy(1, 3);
        String tryDiff = Localization.lang("Try different encoding");
        int answer = JOptionPane.showOptionDialog(frame, builder.getPanel(), SAVE_DATABASE,
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null,
                new String[] { Localization.lang("Save"), tryDiff, Localization.lang("Cancel") }, tryDiff);

        if (answer == JOptionPane.NO_OPTION) {
            // The user wants to use another encoding.
            Object choice = JOptionPane.showInputDialog(frame, Localization.lang("Select encoding"),
                    SAVE_DATABASE, JOptionPane.QUESTION_MESSAGE, null, Encodings.ENCODINGS_DISPLAYNAMES, enc);
            if (choice == null) {
                commit = false;
            } else {
                Charset newEncoding = Charset.forName((String) choice);
                return saveDatabase(file, selectedOnly, newEncoding, saveType);

            }
        } else if (answer == JOptionPane.CANCEL_OPTION) {
            commit = false;
        }

    }

    if (commit) {
        session.commit(file.toPath());
        this.bibDatabaseContext.getMetaData().setEncoding(enc); // Make sure to remember which encoding we used.
    } else {
        session.cancel();
    }

    return commit;
}

From source file:com.netscape.admin.certsrv.Console.java

/**
  * initialize the ldap connection according to all the information. If the directory server is
  * not running, try to start the directory server.
  *//  w  ww  . j a va  2  s  .co m
  * @param info   ConsoleInfo which store the global information.
  * @return   true if successfull. false otherwise.
  */
private final int LDAPinitialization(ConsoleInfo info) {
    // Set DS information;

    Hashtable<String, String> ht = _info.getAuthenticationValues();

    String param;

    // set up configuration data base information

    if ((param = (ht.get("SIE"))) != null)
        _adminServerSIE = param;
    else
        Debug.println("Console:authenticate_user():SIE not found");

    if ((param = (ht.get("ldapHost"))) != null)
        info.setHost(param);
    else
        Debug.println("Console:authenticate_user():ldapHost not found");

    if ((param = (ht.get("ldapPort"))) != null)
        info.setPort(Integer.parseInt(param));
    else
        Debug.println("Console:authenticate_user():ldapPort not found");

    if ((param = (ht.get("ldapBaseDN"))) != null)
        info.setBaseDN(param);
    else
        Debug.println("Console:authenticate_user():ldapBaseDN not found");

    param = (ht.get("ldapSecurity"));
    boolean fLdapSecurity = false;
    if ((param != null) && (param.equals("on"))) {
        info.put("ldapSecurity", "on");
        fLdapSecurity = true;
    } else {
        info.put("ldapSecurity", "off");
    }

    // Need to open an LDAPConnection for the ConsoleInfo object.

    try {
        LDAPConnection ldapConnection = createLDAPConnection(info);
        if (ldapConnection == null) {
            return LDAP_INIT_BIND_FAIL;
        }
        info.setLDAPConnection(ldapConnection);

    } catch (LDAPException le) {

        // DT 5/19/98 Prompt user to restart the registry DS if ldc.connect() failed
        String dsURL = (fLdapSecurity ? "ldaps" : "ldap") + "://" + info.getHost() + ":" + info.getPort();
        String msg = MessageFormat.format(_resource.getString("error", "connectDS"),
                new Object[] { dsURL, le.getMessage() });
        Debug.println("Console:authenticate_user():" + msg);

        if (_dsHasBeenRestarted) {
            // DS has already been restarted, return an error
            JOptionPane.showMessageDialog(com.netscape.management.client.console.SplashScreen.getInstance(),
                    msg, _resource.getString("error", "title"), JOptionPane.ERROR_MESSAGE);
            ModalDialogUtil.sleep();
            return LDAP_INIT_FAILED;
        }

        Object[] choices = { _resource.getString("error", "restartDSButton"),
                _resource.getString("error", "cancelButton") };
        Object[] msgs = { msg, " ", _resource.getString("error", "restartDSMessage"), " " };

        int selection = JOptionPane.showOptionDialog(
                com.netscape.management.client.console.SplashScreen.getInstance(), msgs,
                _resource.getString("error", "inittitle"), JOptionPane.DEFAULT_OPTION,
                JOptionPane.QUESTION_MESSAGE, null, choices, choices[0]);

        if (selection == 1)
            System.exit(1); // cancel

        // Pop a new login dialog, but this is for the Registry DS AS

        /*
                    RestartDialog rd = new RestartDialog(_frame);
                    rd.setDialogLocation(_frame);
                    rd.showModal();
                    if (rd.isCancel())
        System.exit(0);
                    _splashScreen.toFront();
                
                    if (!restartDirectoryServer(rd.getUsername(),
            rd.getPassword(), rd.getURL())) {
        return LDAP_INIT_FAILED;
                    } else {
        msg = _resource.getString("info","restartDS");
        JOptionPane.showMessageDialog(
                com.netscape.management.client.console.SplashScreen.getInstance(), msg,
                _resource.getString("info","restartDSTitle"),
                JOptionPane.INFORMATION_MESSAGE);
        _dsHasBeenRestarted = true;
        return LDAP_INIT_DS_RESTART;
                    }
        */
    }

    // set up user data base information
    // If config DS is unaccessable when authenticate CGI is called, the CGI returns ? for UserDirectory
    if ((param = (ht.get("UserDirectory"))) != null && !param.equals("?")) {
        // this caused I18n problem - param=param.toLowerCase();
        LDAPConnection ldc = null;
        boolean fSSL = false;
        String sHost = info.getHost();
        int iPort = info.getPort();
        String sBaseDN = info.getBaseDN();
        int iStartSearch = 7;
        if (param.startsWith("ldaps://")) {
            fSSL = true;
            iStartSearch = 8;
        }

        int iNextSlash = param.indexOf('/', 8);
        int iNextColon = param.indexOf(':', 8);
        int iNextSpace = param.indexOf(' ', 8); //for failover list

        // if failover list, use the first host and port in the list

        if ((iNextSlash > iNextColon) && (iNextColon != (-1))) {
            // has a port number
            if ((iNextSpace != (-1)) && (iNextSpace < iNextSlash)) {
                // failover list
                iPort = Integer.parseInt(param.substring(iNextColon + 1, iNextSpace));
            } else {
                iPort = Integer.parseInt(param.substring(iNextColon + 1, iNextSlash));
            }
            sHost = param.substring(iStartSearch, iNextColon);
        } else {
            sHost = param.substring(iStartSearch, iNextSlash);
        }

        sBaseDN = param.substring(iNextSlash + 1);
        info.setUserHost(sHost);
        info.setUserPort(iPort);
        info.setUserBaseDN(sBaseDN);

        if (fSSL) {
            ldc = new KingpinLDAPConnection(UtilConsoleGlobals.getLDAPSSLSocketFactory(),
                    info.getAuthenticationDN(), info.getAuthenticationPassword());
        } else {
            ldc = new KingpinLDAPConnection(info.getAuthenticationDN(), info.getAuthenticationPassword());
        }

        try {
            ldc.connect(info.getUserHost(), info.getUserPort());
            ldc.authenticate(LDAPUtil.LDAP_VERSION, info.getAuthenticationDN(),
                    info.getAuthenticationPassword());
        } catch (Exception e) {
            // catch no user exception
            Debug.println("Console: cannot connect to the user database");
        }
        info.setUserLDAPConnection(ldc);
    } else
        Debug.println("Console.authenticate_user():UserDirectory value not found");

    return LDAP_INIT_OK;
}