List of usage examples for java.util Locale getDisplayName
public final String getDisplayName()
From source file:org.openmrs.util.databasechange.ConceptValidatorChangeSet.java
/** * This method is called by the execute {@link #execute(Database)} method to run through all * concept and their conceptNames and validates them, It also tries to fix any constraints that * are being violated./*from w w w . jav a2 s. c o m*/ * * @param connection The database connection */ private void validateAndCleanUpConcepts(JdbcConnection connection) { List<Integer> conceptIds = getAllUnretiredConceptIds(connection); allowedLocales = getAllowedLocalesList(connection); //default locale(if none, then 'en') is always the last in the list. defaultLocale = allowedLocales.get(allowedLocales.size() - 1); //a map to store all duplicates names found for each locale Map<Locale, Set<String>> localeDuplicateNamesMap = null; for (Integer conceptId : conceptIds) { Map<Locale, List<ConceptName>> localeConceptNamesMap = getLocaleConceptNamesMap(connection, conceptId); if (localeConceptNamesMap == null) { updateWarnings.add("No names added for concept with id: " + conceptId); continue; } boolean hasFullySpecifiedName = false; Set<Locale> locales = localeConceptNamesMap.keySet(); List<ConceptName> namesWithNoLocale = null; //for each locale for (Locale conceptNameLocale : locales) { boolean fullySpecifiedNameForLocaleFound = false; boolean preferredNameForLocaleFound = false; boolean shortNameForLocaleFound = false; //map to hold a name and a list of conceptNames that are found as duplicates Map<String, List<ConceptName>> nameDuplicateConceptNamesMap = new HashMap<String, List<ConceptName>>(); //for each name in the locale for (ConceptName nameInLocale : localeConceptNamesMap.get(conceptNameLocale)) { if (StringUtils.isBlank(nameInLocale.getName())) { updateWarnings.add("ConceptName with id " + nameInLocale.getConceptNameId() + " (" + nameInLocale.getName() + ") is null, white space character or empty string"); } //if the concept name has no locale, wonder why this would be the case but there was no not-null constraint originally if (conceptNameLocale == null) { if (namesWithNoLocale == null) { namesWithNoLocale = new LinkedList<ConceptName>(); } namesWithNoLocale.add(nameInLocale); continue; } //The concept's locale should be among the allowed locales listed in global properties if (!allowedLocales.contains(conceptNameLocale)) { updateWarnings.add("ConceptName with id: " + nameInLocale.getConceptNameId() + " (" + nameInLocale.getName() + ") has a locale (" + conceptNameLocale + ") that isn't listed among the allowed ones by the system admin"); } if (nameInLocale.isLocalePreferred() != null) { if (nameInLocale.isLocalePreferred() && !preferredNameForLocaleFound) { if (nameInLocale.isIndexTerm()) { nameInLocale.setLocalePreferred(false); reportUpdatedName(nameInLocale, "Preferred name '" + nameInLocale.getName() + "' in locale '" + conceptNameLocale.getDisplayName() + "' has been dropped as the preferred name because it is a search term"); } else if (nameInLocale.isShort()) { nameInLocale.setLocalePreferred(false); reportUpdatedName(nameInLocale, "Preferred name '" + nameInLocale.getName() + "' in locale '" + conceptNameLocale.getDisplayName() + "' has been dropped as the preferred name because it is a short name"); } else { preferredNameForLocaleFound = true; } } //should have one preferred name per locale else if (nameInLocale.isLocalePreferred() && preferredNameForLocaleFound) { //drop this name as locale preferred so that we have only one nameInLocale.setLocalePreferred(false); reportUpdatedName(nameInLocale, "Preferred name '" + nameInLocale.getName() + "' in locale '" + conceptNameLocale.getDisplayName() + "' has been dropped as the preferred name because there is already another preferred name in the same locale"); } } else { //Enforce not-null on locale preferred field constraint from the database table nameInLocale.setLocalePreferred(false); reportUpdatedName(nameInLocale, "The locale preferred property of name '" + nameInLocale.getName() + "' in locale '" + conceptNameLocale.getDisplayName() + "' has been updated to false from null"); } if (nameInLocale.isFullySpecifiedName()) { if (!hasFullySpecifiedName) { hasFullySpecifiedName = true; } if (!fullySpecifiedNameForLocaleFound) { fullySpecifiedNameForLocaleFound = true; } else { nameInLocale.setConceptNameType(null); reportUpdatedName(nameInLocale, "The name '" + nameInLocale.getName() + "' in locale '" + conceptNameLocale.getDisplayName() + "' has been converted from fully specified to a synonym"); } } if (nameInLocale.isShort()) { if (!shortNameForLocaleFound) { shortNameForLocaleFound = true; } //should have one short name per locale else { nameInLocale.setConceptNameType(null); reportUpdatedName(nameInLocale, "The name '" + nameInLocale.getName() + "' in locale '" + conceptNameLocale.getDisplayName() + "' has been converted from a short name to a synonym"); } } if ((nameInLocale.isFullySpecifiedName() || nameInLocale.isPreferred()) && !isNameUniqueInLocale(connection, nameInLocale, conceptId)) { if (localeDuplicateNamesMap == null) { localeDuplicateNamesMap = new HashMap<Locale, Set<String>>(); } if (!localeDuplicateNamesMap.containsKey(conceptNameLocale)) { localeDuplicateNamesMap.put(conceptNameLocale, new HashSet<String>()); } localeDuplicateNamesMap.get(conceptNameLocale).add(nameInLocale.getName()); } String name = nameInLocale.getName().toLowerCase(); if (!nameDuplicateConceptNamesMap.containsKey(name)) { nameDuplicateConceptNamesMap.put(name, new ArrayList<ConceptName>()); } nameDuplicateConceptNamesMap.get(name).add(nameInLocale); } //close for each name //No duplicate names allowed for the same locale and concept for (Map.Entry<String, List<ConceptName>> entry : nameDuplicateConceptNamesMap.entrySet()) { //no duplicates found for the current name if (entry.getValue().size() < 2) { continue; } logMessages.add( "The name '" + entry.getKey() + "' was found multiple times for the concept with id '" + conceptId + "' in locale '" + conceptNameLocale.getDisplayName() + "'"); /*ConceptName chosenName = null; List<ConceptName> voidedNames = new ArrayList<ConceptName>(); for (ConceptName duplicate : entry.getValue()) { //The first name found should be retained and void the rest of the duplicates if (chosenName == null) chosenName = duplicate; else { duplicate.setVoided(true); duplicate.setVoidReason("Duplicate name in locale"); voidedNames.add(duplicate); reportUpdatedName(duplicate, "ConceptName with id: " + duplicate.getConceptNameId() + " has been voided because it is a duplicate name for concept with id " + conceptId + " in locale '" + conceptNameLocale.getDisplayName() + "'"); } }*/ } //if this locale has no preferred name found, set one if (!preferredNameForLocaleFound) { //find the fully specified name and set it as the locale preferred for (ConceptName cn : localeConceptNamesMap.get(conceptNameLocale)) { if (cn.isFullySpecifiedName()) { cn.setLocalePreferred(true); preferredNameForLocaleFound = true; break; } } //if there was no fully specified name found, mark one of the synonyms as locale preferred if (!preferredNameForLocaleFound) { for (ConceptName cn : localeConceptNamesMap.get(conceptNameLocale)) { if (cn.isSynonym()) { cn.setLocalePreferred(true); break; } } } } } //close for each locale //Make the first name found the fully specified name if none exists if (!hasFullySpecifiedName) { hasFullySpecifiedName = setFullySpecifiedName(conceptId, localeConceptNamesMap); } //set default locale for names with no locale, if there was no fully specified name for the current concept, //set the first name found as the fully specified and drop locale preferred mark and short name concept name type if (!CollectionUtils.isEmpty(namesWithNoLocale)) { for (ConceptName conceptName : namesWithNoLocale) { conceptName.setLocale(defaultLocale); reportUpdatedName(conceptName, "The locale for ConceptName with id " + conceptName.getConceptNameId() + " (" + conceptName.getName() + ") has been set to '" + defaultLocale.getDisplayName() + "'"); if (!hasFullySpecifiedName) { conceptName.setConceptNameType(ConceptNameType.FULLY_SPECIFIED); hasFullySpecifiedName = true; reportUpdatedName(conceptName, "ConceptName with id " + conceptName.getConceptNameId() + " (" + conceptName.getName() + ") in locale '" + defaultLocale.getDisplayName() + "' has been set as the fully specified name for concept with id : " + conceptId); } //convert to a synonym and should not be preferred, this will avoid inconsistencies, incase //already short, fully specified and preferred names exist else { conceptName.setLocalePreferred(false); reportUpdatedName(conceptName, "ConceptName with id " + conceptName.getConceptNameId() + " (" + conceptName.getName() + ") is no longer marked as preferred because it had no locale"); if (conceptName.isFullySpecifiedName() || conceptName.isShort()) { conceptName.setConceptNameType(null); reportUpdatedName(conceptName, "The name '" + conceptName.getName() + "' in locale '" + conceptName.toString() + "' has been converted to a synonym because it had no locale"); } } } } if (!hasFullySpecifiedName) { updateWarnings.add("Concept with id: " + conceptId + " has no fully specified name"); } } if (!MapUtils.isEmpty(localeDuplicateNamesMap)) { for (Map.Entry<Locale, Set<String>> entry : localeDuplicateNamesMap.entrySet()) { //no duplicates found in the locale if (CollectionUtils.isEmpty(entry.getValue())) { continue; } for (String duplicateName : entry.getValue()) { updateWarnings.add("Concept Name '" + duplicateName + "' was found multiple times in locale '" + entry.getKey() + "'"); } } } logMessages.add("Number of Updated ConceptNames: " + updatedConceptNames.size()); }
From source file:com.osparking.osparking.Settings_System.java
private void SettingsSaveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SettingsSaveButtonActionPerformed Connection conn = null;//from w ww .ja va2s .c o m PreparedStatement updateSettings = null; int result = -1; boolean newStorePassingDelay = RecordPassingDelayChkBox.isSelected(); Locale locale = LanguageBox.getLocale(); boolean langNotSupported = (!locale.equals(defaultLocale) && !locale.equals(enUS_Locale)); if (langNotSupported) { String message = WRONG_LANG_DIALOG_1.getContent() + System.lineSeparator(); message += WRONG_LANG_DIALOG_2.getContent() + locale.getDisplayName() + System.lineSeparator() + System.lineSeparator(); message += WRONG_LANG_DIALOG_3.getContent() + System.lineSeparator(); message += WRONG_LANG_DIALOG_4.getContent() + defaultLocale.getDisplayName() + ", " + enUS_Locale.getDisplayName() + System.lineSeparator(); JOptionPane.showConfirmDialog(this, message, LANGUAGE_ERROR_TITLE.getContent(), JOptionPane.PLAIN_MESSAGE, WARNING_MESSAGE); return; } //<editor-fold desc="--check setting input errors"> if (!TextFieldNumericValueOK(TextFieldPicWidth, "Photo Extent Typing Errors")) { return; } if (!TextFieldNumericValueOK(TextFieldPicHeight, "Photo Height Typing Errors")) { return; } if (Integer.parseInt(removeNonNumeric(TextFieldPicHeight.getText().trim())) < 100) { TextFieldPicHeight.requestFocusInWindow(); JOptionPane.showConfirmDialog(this, "Please enter a height value of 100 or more", "Picture Height Input Error", JOptionPane.PLAIN_MESSAGE, WARNING_MESSAGE); return; } if (Integer.parseInt(removeNonNumeric(TextFieldPicWidth.getText().trim())) < 100) { TextFieldPicWidth.requestFocusInWindow(); JOptionPane.showConfirmDialog(this, "Please enter a width value of 100 or more", "Picture Width Input Error", JOptionPane.PLAIN_MESSAGE, WARNING_MESSAGE); return; } if (someIPaddressWrong()) { return; } if (someCOMportIDsame()) { return; } //</editor-fold> int newStatCount = 0; short pwLevel = -1; short optnLogLevel = -1; String maxLineStr = ""; int imageKeepDuration = 0; int picWidth = Integer.parseInt(removeNonNumeric(TextFieldPicWidth.getText())); int picHeight = Integer.parseInt(removeNonNumeric(TextFieldPicHeight.getText())); int flowCycle = Integer.parseInt(removeNonNumeric((String) FlowingComboBox.getSelectedItem())); int blinkCycle = Integer.parseInt(removeNonNumeric(TextFieldPicWidth.getText())); boolean gateCountChanged = false; try { StringBuffer sb = new StringBuffer("Update SettingsTable SET "); //<editor-fold desc="--create update statement"> sb.append("Lot_Name = ?, "); sb.append("perfEvalNeeded = ?, PWStrengthLevel = ?, OptnLoggingLevel = ?, "); sb.append("languageCode = ?, countryCode = ?, localeIndex = ?, statCount = ?, "); sb.append("MaxMessageLines = ?, GateCount = ?, "); sb.append("PictureWidth = ?, PictureHeight = ?, "); sb.append("EBD_flow_cycle = ?, EBD_blink_cycle = ?, "); sb.append("max_maintain_date = ? "); //</editor-fold> ConvComboBoxItem selectedItem = (ConvComboBoxItem) PopSizeCBox.getSelectedItem(); newStatCount = (Integer) selectedItem.getKeyValue(); if (newStorePassingDelay) { for (int gateID = 1; gateID <= gateCount; gateID++) { initPassingDelayStatIfNeeded(newStatCount, gateID); } } conn = JDBCMySQL.getConnection(); updateSettings = conn.prepareStatement(sb.toString()); int pIndex = 1; // <editor-fold defaultstate="collapsed" desc="--Provide values to each parameters of the UPDATE statement"> updateSettings.setString(pIndex++, lotNameTextField.getText().trim()); if (newStorePassingDelay) { updateSettings.setInt(pIndex++, 1); } else { updateSettings.setInt(pIndex++, 0); if (DEBUG) { // Give warning that in debug mode PassingDelay is always recorded. JOptionPane.showMessageDialog(null, RECORD_DELAY_DEBUG.getContent()); } } pwLevel = (short) (PWStrengthChoiceComboBox.getSelectedIndex()); updateSettings.setShort(pIndex++, pwLevel); optnLogLevel = (short) (OptnLoggingLevelComboBox.getSelectedIndex()); updateSettings.setShort(pIndex++, optnLogLevel); updateSettings.setString(pIndex++, LanguageBox.getLocale().getLanguage()); updateSettings.setString(pIndex++, LanguageBox.getLocale().getCountry()); updateSettings.setShort(pIndex++, (short) LanguageBox.getSelectedIndex()); updateSettings.setInt(pIndex++, PopSizeCBox.getSelectedIndex()); maxLineStr = (String) MessageMaxLineComboBox.getSelectedItem(); updateSettings.setShort(pIndex++, new Short(maxLineStr)); updateSettings.setShort(pIndex++, new Short((String) GateCountComboBox.getSelectedItem())); updateSettings.setInt(pIndex++, picWidth); updateSettings.setInt(pIndex++, picHeight); updateSettings.setInt(pIndex++, flowCycle); updateSettings.setInt(pIndex++, blinkCycle); ConvComboBoxItem item = (ConvComboBoxItem) ImageDurationCBox.getSelectedItem(); imageKeepDuration = (Integer) (item.getKeyValue()); updateSettings.setInt(pIndex++, imageKeepDuration); // </editor-fold> result = updateSettings.executeUpdate(); if (index2Level(opLoggingIndex) != Level.OFF && index2Level(optnLogLevel) == Level.OFF) { Globals.isFinalWishLog = true; } } catch (SQLException se) { Globals.logParkingException(Level.SEVERE, se, "(Save settings: " + (newStorePassingDelay ? "Y" : "N") + ")"); } finally { // <editor-fold defaultstate="collapsed" desc="--Return resources and display the save result"> closeDBstuff(conn, updateSettings, null, "(Save settings: " + (newStorePassingDelay ? "Y" : "N") + ")"); if (result == 1) { //<editor-fold desc="-- Log system settings change if set to do so"> if (statCount != newStatCount) { logParkingOperation(OpLogLevel.SettingsChange, "Settings Change, Statistics Population Size: " + statCount + " => " + newStatCount); } if (storePassingDelay != newStorePassingDelay) { logParkingOperation(OpLogLevel.SettingsChange, "Settings Change, Average Passing Delay: " + storePassingDelay + " => " + newStorePassingDelay); } if (pwStrengthLevel != pwLevel) { logParkingOperation(OpLogLevel.SettingsChange, "Settings Change, Password Strength Level: " + PWStrengthChoiceComboBox.getItemAt(pwStrengthLevel) + " => " + PWStrengthChoiceComboBox.getItemAt(pwLevel)); } if (opLoggingIndex != optnLogLevel) { logParkingOperation(OpLogLevel.LogAlways, "Settings Change, Gen' Operation Log Level: " + OptnLoggingLevelComboBox.getItemAt(opLoggingIndex) + " => " + OptnLoggingLevelComboBox.getItemAt(optnLogLevel)); } if (localeIndex != (short) LanguageBox.getSelectedIndex()) { logParkingOperation(OpLogLevel.SettingsChange, "Settings Change, Date Chooser Lang': " + LanguageBox.getItemAt(localeIndex) + " => " + LanguageBox.getItemAt((short) LanguageBox.getSelectedIndex())); } if (maxMessageLines != new Short(maxLineStr)) { logParkingOperation(OpLogLevel.SettingsChange, "Settings Change, Recent Event Line Max: " + maxMessageLines + " => " + new Short(maxLineStr)); } short newGateCount = new Short((String) GateCountComboBox.getSelectedItem()); gateCountChanged = gateCount != newGateCount; if (gateCountChanged) { logParkingOperation(OpLogLevel.SettingsChange, "Settings Change, Number of Gates: " + gateCount + " => " + newGateCount); } if (maxMaintainDate != imageKeepDuration) { logParkingOperation(OpLogLevel.SettingsChange, "Settings Change, Image Keep Duration: " + maxMaintainDate + " => " + imageKeepDuration); } if (PIC_WIDTH != picWidth) { logParkingOperation(OpLogLevel.SettingsChange, "Settings Change, Image width: " + PIC_WIDTH + " => " + picWidth); } if (PIC_HEIGHT != picHeight) { logParkingOperation(OpLogLevel.SettingsChange, "Settings Change, Image Height: " + PIC_HEIGHT + " => " + picHeight); } if (EBD_flowCycle != flowCycle) { logParkingOperation(OpLogLevel.UserCarChange, "E-Board Settings Change, Cycles--flowing: " + EBD_flowCycle + " => " + flowCycle); } if (EBD_blinkCycle != blinkCycle) { logParkingOperation(OpLogLevel.UserCarChange, "E-Board Settings Change, Cycles--blinking: " + EBD_blinkCycle + " => " + blinkCycle); } if (mainForm != null && gateCountChanged) { JOptionPane.showMessageDialog(mainForm, REBOOT_MESSAGE.getContent(), REBOOT_POPUP.getContent(), WARNING_MESSAGE, new javax.swing.ImageIcon(mainForm.getClass().getResource("/restart.png"))); mainForm.askUserIntentionOnProgramStop(true); } //</editor-fold> Globals.getOperationLog().setLevel(index2Level(opLoggingIndex)); } else { JOptionPane.showMessageDialog(this, FAIL_SAVE_SETTINGS_DIALOG.getContent(), SETTINGS_SAVE_RESULT.getContent(), JOptionPane.ERROR_MESSAGE); } // </editor-fold> } boolean majorChange[] = new boolean[] { false }; result += saveGateDevices(majorChange); if (mainForm != null && (gateCountChanged || majorChange[0])) { JOptionPane.showMessageDialog(mainForm, REBOOT_MESSAGE.getContent(), REBOOT_POPUP.getContent(), WARNING_MESSAGE, new javax.swing.ImageIcon(mainForm.getClass().getResource("/restart.png"))); mainForm.askUserIntentionOnProgramStop(true); } if (result == gateCount + 1) { readSettings(); Globals.getOperationLog().setLevel(index2Level(opLoggingIndex)); JOptionPane.showMessageDialog(this, SAVE_SETTINGS_DIALOG.getContent(), SETTINGS_SAVE_RESULT.getContent(), JOptionPane.PLAIN_MESSAGE); enableSaveCancelButtons(false); } else { JOptionPane.showMessageDialog(this, FAIL_SAVE_SETTINGS_DIALOG.getContent(), SETTINGS_SAVE_RESULT.getContent(), JOptionPane.ERROR_MESSAGE); } }
From source file:edu.ku.brc.specify.config.SpecifyAppContextMgr.java
/** * @param databaseName// w ww. ja v a 2s . c om * @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:com.globalsight.webservices.Ambassador.java
/** * @deprecated Returns an XML description containing URLs to a localized * document for each workflow in the desired job if the job has * been exported./*w w w . j a v a 2 s. co m*/ * * @param p_accessToken * @param p_jobName * Job name * @return String An XML description which contains URLs to a localized * document for each workflow if the job has been exported * @throws WebServiceException */ public String getLocalizedDocuments_old(String p_accessToken, String p_jobName) throws WebServiceException { checkAccess(p_accessToken, GET_LOCALIZED_DOCUMENTS); checkPermission(p_accessToken, Permission.JOBS_VIEW); String jobName = p_jobName; Job job = queryJob(jobName, p_accessToken); long jobId = job.getId(); String status = job.getState(); if (status == null) throw new WebServiceException("Job " + jobName + " does not exist."); // query all the target pages for the workflows for this job StringBuffer sql = new StringBuffer(); sql.append("select source_page.external_page_id, locale.iso_lang_code, ") .append("locale.iso_country_code, target_page.export_sub_dir") .append(" from job, workflow, request, source_page, locale, target_page") .append(" where job.name=?").append(" and workflow.job_id=job.id") .append(" and request.job_id=job.id").append(" and source_page.id=request.page_id") .append(" and locale.id=workflow.target_locale_id") .append(" and source_page.id=target_page.source_page_id") .append(" and workflow.iflow_instance_id = target_page.workflow_iflow_instance_id") .append(" and target_page.state =?"); StringBuffer xml = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n"); xml.append("<localizedDocuments>\r\n"); xml.append("<jobId>").append(jobId).append("</jobId>\r\n"); xml.append("<jobName>").append(EditUtil.encodeXmlEntities(jobName)).append("</jobName>\r\n"); xml.append("<jobStatus>").append(status).append("</jobStatus>\r\n"); Connection connection = null; PreparedStatement query = null; ResultSet results = null; try { connection = ConnectionPool.getConnection(); query = connection.prepareStatement(sql.toString()); query.setString(1, jobName); query.setString(2, "EXPORTED"); results = query.executeQuery(); boolean gotSomeResult = false; StringBuilder urlPrefix = new StringBuilder(); urlPrefix.append(getUrl()).append("/cxedocs/"); String company = CompanyWrapper.getCompanyNameById(job.getCompanyId()); urlPrefix.append(URLEncoder.encode(company, "utf-8")); while (results.next()) { String fileName = results.getString(1); String langCode = results.getString(2); String countryCode = results.getString(3); String exportSubDir = results.getString(4); StringBuffer locale = new StringBuffer(langCode); locale.append("_").append(countryCode); String targetFileName = File.separator + replaceLocaleInFileName(fileName, exportSubDir, locale.toString()); targetFileName = targetFileName.replace('\\', '/'); String encodedTargetFileName = ""; // String[] names = targetFileName.split("/"); // for(int i = 0; i < names.length; i++) // { // encodedTargetFileName = encodedTargetFileName + "/" + // URLEncoder.encode(names[i]); // } encodedTargetFileName = URLEncoder.encodeUrlString(targetFileName); xml.append("<targetPage locale=\"").append(locale.toString()).append("\""); Locale l = new Locale(langCode, countryCode); xml.append(" localeDisplayName=\"").append(l.getDisplayName()).append("\">"); xml.append(urlPrefix).append(targetFileName); xml.append("</targetPage>\r\n"); gotSomeResult = true; } if (!gotSomeResult) throw new WebServiceException("No documents for job name " + jobName); } catch (ConnectionPoolException cpe) { logger.error("Unable to connect to database to get localized documents.", cpe); } catch (SQLException sqle) { logger.error("Unable to query DB for localized documents.", sqle); } finally { releaseDBResource(results, query, connection); } xml.append("</localizedDocuments>\r\n"); return xml.toString(); }