Example usage for javax.swing JOptionPane showOptionDialog

List of usage examples for javax.swing JOptionPane showOptionDialog

Introduction

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

Prototype

@SuppressWarnings("deprecation")
public static int showOptionDialog(Component parentComponent, Object message, String title, int optionType,
        int messageType, Icon icon, Object[] options, Object initialValue) throws HeadlessException 

Source Link

Document

Brings up a dialog with a specified icon, where the initial choice is determined by the initialValue parameter and the number of choices is determined by the optionType parameter.

Usage

From source file:edu.ku.brc.specify.tools.StrLocalizerApp.java

/**
 * @return true if no unsaved changes are present
 * else return results of prompt to save
 *//* w w  w. ja v  a 2s.  c om*/
protected boolean checkForChanges() {
    int s = termList.getSelectedIndex();
    if (s != -1) {
        StrLocaleEntry entry = srcFile.getKey(s);
        entry.setDstStr(textField.getText());
    }
    if (srcFile.isEdited()) {
        int response = JOptionPane.showOptionDialog((Frame) getTopWindow(),
                String.format(getResourceString("StrLocalizerApp.SaveChangesMsg"), destFile.getPath()),
                getResourceString("StrLocalizerApp.SaveChangesTitle"), JOptionPane.YES_NO_CANCEL_OPTION,
                JOptionPane.QUESTION_MESSAGE, null, null, JOptionPane.YES_OPTION);
        if (response == JOptionPane.CANCEL_OPTION) {
            return false;
        }
        if (response == JOptionPane.YES_OPTION) {
            doSave();
            return true; //what if it fails? 
        }
    }
    return true;
}

From source file:edu.ku.brc.specify.tasks.InteractionsTask.java

/**
 * @param cmdAction/* w w  w.j  ava  2 s .co m*/
 */
protected void checkToPrintLoan(final CommandAction cmdAction) {
    boolean isGift = cmdAction.getData() instanceof Gift;
    if (cmdAction.getData() instanceof Loan || isGift) {
        Loan loan = isGift ? null : (Loan) cmdAction.getData();
        Gift gift = isGift ? (Gift) cmdAction.getData() : null;

        Boolean doPrintInvoice = null;
        FormViewObj formViewObj = getCurrentFormViewObj();
        if (formViewObj != null) {
            Component comp = formViewObj.getControlByName("generateInvoice");
            if (comp instanceof JCheckBox) {
                doPrintInvoice = ((JCheckBox) comp).isSelected();
            }
        }

        if (doPrintInvoice == null) {
            String number = isGift ? gift.getGiftNumber() : loan.getLoanNumber();
            String btnLbl = getResourceString(isGift ? "GIFT" : "LOAN");
            String msg = getLocalizedMessage("CreateInvoiceForNum", getResourceString(isGift ? "GIFT" : "LOAN"),
                    number);
            Object[] options = { btnLbl, getResourceString("CANCEL") };
            int n = JOptionPane.showOptionDialog(UIRegistry.get(UIRegistry.FRAME), msg, btnLbl,
                    JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, //don't use a custom Icon
                    options, //the titles of buttons
                    options[0]); //default button title
            doPrintInvoice = n == 0;
        }

        // XXX DEBUG
        //printLoan = false;
        if (doPrintInvoice) {
            InfoForTaskReport invoice = getReport(isGift);

            if (invoice == null) {
                return;
            }

            DataProviderSessionIFace session = null;
            try {
                session = DataProviderFactory.getInstance().createSession();
                //session.attach(loan);

                String hql = isGift ? "FROM Gift WHERE giftId = " + gift.getGiftId()
                        : "FROM Loan WHERE loanId = " + loan.getLoanId();

                loan = isGift ? null : (Loan) session.getData(hql);
                gift = isGift ? (Gift) session.getData(hql) : null;

                Set<Shipment> shipments = isGift ? gift.getShipments() : loan.getShipments();
                boolean keepGoing = true;
                if (invoice.getSpReport() == null) {
                    if (shipments != null && shipments.size() == 0) {
                        UIRegistry.displayErrorDlg(String.format(getResourceString("NO_SHIPMENTS_ERROR"),
                                invoice.getSpAppResource().getName()));
                        keepGoing = false;
                    } else if (shipments != null && shipments.size() > 1) {
                        // XXX Do we allow them to pick a shipment or print all?
                        UIRegistry.displayErrorDlg(
                                String.format(getResourceString("MULTI_SHIPMENTS_NOT_SUPPORTED"),
                                        invoice.getSpAppResource().getName()));
                        keepGoing = false;
                    } //else
                      //{
                      // XXX At the moment this is just checking to see if there is at least one "good/valid" shipment
                      // but the hard part will be sending the correct info so the report can be printed
                      // using both a Loan Id and a Shipment ID, and at some point distinguishing between using
                      // the shipped by versus the shipper.
                      //                        Shipment shipment = isGift ? gift.getShipments().iterator().next() : loan.getShipments().iterator().next();
                      //                        if (shipment.getShippedBy() == null)
                      //                        {
                      //                            UIRegistry.displayErrorDlg(getResourceString("SHIPMENT_MISSING_SHIPPEDBY"));
                      //                            
                      //                        } else if (shipment.getShippedBy().getAddresses().size() == 0)
                      //                        {
                      //                            UIRegistry.displayErrorDlg(getResourceString("SHIPPEDBY_MISSING_ADDR"));
                      //                        } else if (shipment.getShippedTo() == null)
                      //                        {
                      //                            UIRegistry.displayErrorDlg(getResourceString("SHIPMENT_MISSING_SHIPPEDTO"));
                      //                        } else if (shipment.getShippedTo().getAddresses().size() == 0)
                      //                        {
                      //                            UIRegistry.displayErrorDlg(getResourceString("SHIPPEDTO_MISSING_ADDR"));
                      //                        } else
                      //                        {
                }
                if (keepGoing) {
                    String identTitle;
                    int tableId;
                    Integer id;
                    if (isGift) {
                        identTitle = gift.getIdentityTitle();
                        tableId = gift.getTableId();
                        id = gift.getId();
                    } else {
                        identTitle = loan.getIdentityTitle();
                        tableId = loan.getTableId();
                        id = loan.getId();
                    }

                    RecordSet rs = new RecordSet();
                    rs.initialize();
                    rs.setName(identTitle);
                    rs.setDbTableId(tableId);
                    rs.addItem(id);

                    dispatchReport(invoice, rs, "LoanInvoice");
                }

            } finally {
                if (session != null) {
                    session.close();
                }
            }
        }
    }
}

From source file:edu.ku.brc.ui.UIRegistry.java

/**
 * Display an Confirmation Dialog where everything comes from the bundle.
 * @param titleKey the key to the dialog title
 * @param msgKey the key to the dialog message
 * @param keyBtn1 the key to the first button 
 * @param keyBtn2 the key to the second button
 * @param iconOption the icon to show//from  w ww . j a  v  a 2 s  .  co m
 * @return true is YES false if NO
 */
public static boolean displayConfirm(final String title, final String msg, final String keyBtn1, // Yes
        final String keyBtn2, // No
        final int iconOption) {
    // Custom button text
    // NOTE: clicking the 'X' returns a -1
    Object[] options = { keyBtn1, keyBtn2 };

    return JOptionPane.showOptionDialog(getMostRecentWindow(), msg, title, JOptionPane.YES_NO_OPTION,
            iconOption, null, options, options[1]) == JOptionPane.YES_OPTION;
}

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

/**
 * @param databaseName/*from ww w.j  a  v  a2 s .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:de.dal33t.powerfolder.Controller.java

/**
 * Call to notify the Controller of a problem while binding a required
 * listening socket./*w  w  w.  j  ava2s .c o  m*/
 *
 * @param ports
 */
private void portBindFailureProblem(String ports) {
    if (!isUIEnabled()) {
        logSevere("Unable to open incoming port from the portlist: " + ports);
        exit(1);
        return;
    }

    // Must use JOptionPane here because there is no Controller yet for
    // DialogFactory!
    int response = JOptionPane.showOptionDialog(null,
            Translation.getTranslation("dialog.bind_error.option.text"),
            Translation.getTranslation("dialog.bind_error.option.title"), JOptionPane.YES_NO_OPTION,
            JOptionPane.WARNING_MESSAGE, null,
            new String[] { Translation.getTranslation("dialog.bind_error.option.ignore"),
                    Translation.getTranslation("dialog.bind_error.option.exit") },
            0);
    switch (response) {
    case 1:
        exit(0);
        break;
    default:
        bindRandomPort();
        break;
    }
}

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();/*from www  .  j av a  2s . c om*/
    } 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
 *//*from w w w  .j a  v a2s .c  om*/
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:edu.ku.brc.ui.UIRegistry.java

/**
 * Display an Confirmation Dialog where everything comes from the bundle.
 * @param titleKey the key to the dialog title
 * @param msgKey the key to the dialog message
 * @param keyBtn1 the key to the first button 
 * @param keyBtn2 the key to the second button
 * @param keyBtn3 the key to the third button
 * @param iconOption the icon to show//from  www  .  java2 s.  com
 * @return YES_OPTION, NO_OPTION, CANCEL_OPTION
 */
public static int displayConfirm(final String title, final String msg, final String keyBtn1, // Yes
        final String keyBtn2, // No
        final String keyBtn3, // Cancel
        final int iconOption) {
    // Custom button text
    Object[] options = { keyBtn1, keyBtn2, keyBtn3 };

    return JOptionPane.showOptionDialog(getMostRecentWindow(), msg, title, JOptionPane.YES_NO_CANCEL_OPTION,
            iconOption, null, options, options[2]);
}

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;// w w w  .j av a 2  s .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.
  *//ww w  . j av  a  2  s .  c  o 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;
}