List of usage examples for java.util Locale equals
@Override public boolean equals(Object obj)
From source file:net.spfbl.core.User.java
/** * Change locale of user.//ww w .j a va 2 s. co m * @param token locale pattern. * @return true if value was changed.LocaleUtils.toLocale(language); */ public boolean setLocale(String token) { if (token == null) { return false; } else { Locale newLocale = LocaleUtils.toLocale(token); if (newLocale == null) { return false; } else if (newLocale.equals(this.locale)) { return false; } else { this.locale = newLocale; return CHANGED = true; } } }
From source file:edu.ku.brc.specify.config.SpecifyAppContextMgr.java
/** * @param databaseName/* w w w . j av a 2 s . c o m*/ * @param userName * @param startingOver * @param doPrompt * @param collectionName * @return */ public CONTEXT_STATUS setContext(final String databaseName, final String userName, final boolean startingOver, final boolean doPrompt, final boolean isFirstTime, final String collectionName, final boolean isMainSpecifyApp) { if (debug) log.debug("setting context - databaseName: [" + databaseName + "] userName: [" + userName + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ this.databaseName = databaseName; this.userName = userName; this.hasContext = true; if (isFirstTime) { DBTableIdMgr.getInstance().clearPermissions(); } // This is where we will read it in from the Database // but for now we don't need to do that. // // We need to search for User, Collection, Discipline and UserType // Then DataProviderSessionIFace session = null; try { session = openSession(); } catch (org.hibernate.exception.SQLGrammarException ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifyAppContextMgr.class, ex); showLocalizedError(L10N + "SCHEMA_OUTOF_SYNC"); //$NON-NLS-1$ System.exit(0); } if (session == null) { return CONTEXT_STATUS.Error; } try { List<?> list = session.getDataList(SpecifyUser.class, "name", userName); //$NON-NLS-1$ if (list.size() == 1) { user = (SpecifyUser) list.get(0); user.getAgents().size(); // makes sure the Agent is not lazy loaded session.evict(user.getAgents()); setClassObject(SpecifyUser.class, user); if (!startingOver && isMainSpecifyApp) { if (user.getIsLoggedIn()) { Object[] options = { getResourceString(L10N + "OVERRIDE"), //$NON-NLS-1$ getResourceString(L10N + "EXIT") //$NON-NLS-1$ }; int userChoice = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(), getResourceString(L10N + "LOGGED_IN"), getResourceString(L10N + "LOGGED_IN_TITLE"), //$NON-NLS-2$ JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (userChoice == JOptionPane.NO_OPTION) { //CommandDispatcher.dispatch(new CommandAction("App", "AppReqExit")); System.exit(0); } } user.setIsLoggedIn(true); user.setLoginOutTime(new Timestamp(System.currentTimeMillis())); try { session.beginTransaction(); session.saveOrUpdate(user); session.commit(); } catch (Exception ex) { session.rollback(); edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifyAppContextMgr.class, ex); log.error(ex); } } } else { //JOptionPane.showMessageDialog(null, // getResourceString("USER_NOT_FOUND"), // getResourceString("USER_NOT_FOUND_TITLE"), JOptionPane.WARNING_MESSAGE); return CONTEXT_STATUS.Error; //throw new RuntimeException("The user ["+userName+"] could not be located as a Specify user."); } // First we start by getting all the Collection that the User want to // work with for this "Context" then we need to go get all the Default View and // additional XML Resources. if (isFirstTime) { FixDBAfterLogin.fixUserPermissions(false); } if (!AppPreferences.getGlobalPrefs().getBoolean("ExsiccataUpdateFor1_7", false)) { FixDBAfterLogin.fixExsiccata(); } Collection curColl = getClassObject(Collection.class); int prevCollectionId = curColl != null ? curColl.getCollectionId() : -1; Discipline curDis = getClassObject(Discipline.class); int prevDisciplineId = curDis != null ? curDis.getDisciplineId() : -1; classObjHash.clear(); setClassObject(SpecifyUser.class, user); // Ask the User to choose which Collection they will be working with Collection collection = setupCurrentCollection(user, doPrompt, collectionName); if (collection == null) { // Return false but don't mess with anything that has been set up so far currentStatus = currentStatus == CONTEXT_STATUS.Initial ? CONTEXT_STATUS.Error : CONTEXT_STATUS.Ignore; return currentStatus; } collection = session.merge(collection); String userType = user.getUserType(); if (debug) log.debug("User[" + user.getName() + "] Type[" + userType + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ userType = StringUtils.replace(userType, " ", "").toLowerCase(); //$NON-NLS-1$ //$NON-NLS-2$ if (debug) log.debug("Def Type[" + userType + "]"); //$NON-NLS-1$ //$NON-NLS-2$ spAppResourceList.clear(); viewSetHash.clear(); Discipline discipline = session.getData(Discipline.class, "disciplineId", //$NON-NLS-1$ collection.getDiscipline().getId(), DataProviderSessionIFace.CompareType.Equals); discipline.forceLoad(); setClassObject(Discipline.class, discipline); String disciplineStr = discipline.getType().toLowerCase(); Division division = discipline.getDivision(); division.forceLoad(); setClassObject(Division.class, division); DataType dataType = discipline.getDataType(); dataType.forceLoad(); setClassObject(DataType.class, dataType); Agent userAgent = null; for (Agent agt : user.getAgents()) { if (agt.getDivision().getId().equals(division.getId())) { userAgent = agt; userAgent.getAddresses().size(); userAgent.getVariants().size(); break; } } setClassObject(Agent.class, userAgent); IconEntry ceEntry = IconManager.getIconEntryByName("CollectingEvent"); if (ceEntry != null) { boolean isEmbedded = collection.getIsEmbeddedCollectingEvent(); IconEntry ciEntry = IconManager .getIconEntryByName(isEmbedded ? "collectinginformation" : "ce_restore"); if (ciEntry != null) { ceEntry.setIcon(ciEntry.getIcon()); ceEntry.getIcons().clear(); } } if (isFirstTime) { AppPreferences.startup(); //-------------------------------------------------------------------------------- // Check for locks set on uploader, tree update, ... //-------------------------------------------------------------------------------- int uploadLockCheckResult = Uploader.checkUploadLock(null); boolean noLocks = uploadLockCheckResult != Uploader.LOCKED; boolean goodTrees = true; if (uploadLockCheckResult != Uploader.LOCK_IGNORED) { if (noLocks) { if (!discipline.getTaxonTreeDef().checkNodeRenumberingLock()) { noLocks = false; UIRegistry.showLocalizedError("Specify.TreeUpdateLock", discipline.getTaxonTreeDef().getName()); } } if (noLocks) { if (!discipline.getGeographyTreeDef().checkNodeRenumberingLock()) { noLocks = false; UIRegistry.showLocalizedError("Specify.TreeUpdateLock", discipline.getGeographyTreeDef().getName()); } } if (noLocks) { if (!division.getInstitution().getStorageTreeDef().checkNodeRenumberingLock()) { noLocks = false; UIRegistry.showLocalizedError("Specify.TreeUpdateLock", division.getInstitution().getStorageTreeDef().getName()); } } if (noLocks && discipline.getGeologicTimePeriodTreeDef() != null) { if (!discipline.getGeologicTimePeriodTreeDef().checkNodeRenumberingLock()) { noLocks = false; UIRegistry.showLocalizedError("Specify.TreeUpdateLock", discipline.getGeologicTimePeriodTreeDef().getName()); } } if (noLocks && discipline.getLithoStratTreeDef() != null) { if (!discipline.getLithoStratTreeDef().checkNodeRenumberingLock()) { noLocks = false; UIRegistry.showLocalizedError("Specify.TreeUpdateLock", discipline.getLithoStratTreeDef().getName()); } } if (noLocks) { // Now force node number updates for trees that are // out-of-date goodTrees = discipline.getTaxonTreeDef().checkNodeNumbersUpToDate(true); if (goodTrees) { goodTrees = discipline.getGeographyTreeDef().checkNodeNumbersUpToDate(true); } if (goodTrees) { goodTrees = division.getInstitution().getStorageTreeDef() .checkNodeNumbersUpToDate(true); } if (goodTrees && discipline.getGeologicTimePeriodTreeDef() != null) { goodTrees = discipline.getGeologicTimePeriodTreeDef().checkNodeNumbersUpToDate(true); } if (goodTrees && discipline.getLithoStratTreeDef() != null) { goodTrees = discipline.getLithoStratTreeDef().checkNodeNumbersUpToDate(true); } } } if (!noLocks || !goodTrees) { user.setIsLoggedIn(false); user.setLoginOutTime(new Timestamp(System.currentTimeMillis())); try { session.beginTransaction(); session.saveOrUpdate(user); session.commit(); } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifyAppContextMgr.class, ex); log.error(ex); } System.exit(0); } else { user.setLoginCollectionName(collection.getCollectionName()); user.setLoginDisciplineName(discipline.getName()); try { session.beginTransaction(); session.saveOrUpdate(user); session.commit(); } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifyAppContextMgr.class, ex); log.error(ex); } } } DisciplineType disciplineType = DisciplineType.getDiscipline(discipline.getType()); String folderName = disciplineType.getFolder(); //--------------------------------------------------------- // This is the Full Path User / Discipline / Collection / UserType / isPersonal // For example: rods/fish/fish/manager / true (meaning the usr's personal space) //--------------------------------------------------------- String title = getResourceString(L10N + "" + PERSONALDIR); SpAppResourceDir appResDir = getAppResDir(session, user, discipline, collection, userType, true, title, true); //System.out.println("PERSONALDIR Dir: "+appResDir.getId()+", UT: "+appResDir.getUserType()+", IsPers: "+appResDir.getIsPersonal()+", Disp: "+appResDir.getDisciplineType()); spAppResourceList.add(appResDir); spAppResourceHash.put(PERSONALDIR, appResDir); viewSetMgrHash.put(PERSONALDIR, new Pair<String, File>(null, null)); //--------------------------------------------------------- // This is the Full Path User / Discipline / Collection / UserType // For example: rods/fish/fish/manager //--------------------------------------------------------- title = getResourceString(L10N + "" + USERTYPEDIR); appResDir = getAppResDir(session, user, discipline, collection, userType, false, title, true); //System.out.println("USERTYPEDIR Dir: "+appResDir.getId()+", UT: "+appResDir.getUserType()+", IsPers: "+appResDir.getIsPersonal()+", Disp: "+appResDir.getDisciplineType()); File dir = XMLHelper.getConfigDir(folderName + File.separator + userType); if (dir.exists()) { mergeAppResourceDirFromDiskDir(USERTYPEDIR, appResDir, disciplineStr + " " + userType, dir); //$NON-NLS-1$ } spAppResourceList.add(appResDir); spAppResourceHash.put(USERTYPEDIR, appResDir); //--------------------------------------------------------- // This is the Full Path User / Discipline / Collection // For example: rods/fish/fish //--------------------------------------------------------- title = getResourceString(L10N + "" + COLLECTIONDIR); appResDir = getAppResDir(session, user, discipline, collection, null, false, title, true); //System.out.println("COLLECTIONDIR Dir: "+appResDir.getId()+", UT: "+appResDir.getUserType()+", IsPers: "+appResDir.getIsPersonal()+", Disp: "+appResDir.getDisciplineType()); spAppResourceList.add(appResDir); spAppResourceHash.put(COLLECTIONDIR, appResDir); viewSetMgrHash.put(COLLECTIONDIR, new Pair<String, File>(null, null)); //--------------------------------------------------------- // This is the Full Path User / Discipline // For example: rods/fish //--------------------------------------------------------- title = getResourceString(L10N + "" + DISCPLINEDIR); appResDir = getAppResDir(session, user, discipline, null, null, false, title, true); //System.out.println("DISCPLINEDIR Dir: "+appResDir.getId()+", UT: "+appResDir.getUserType()+", IsPers: "+appResDir.getIsPersonal()+", Disp: "+appResDir.getDisciplineType()); dir = XMLHelper.getConfigDir(folderName); if (dir.exists()) { mergeAppResourceDirFromDiskDir(DISCPLINEDIR, appResDir, disciplineStr, dir); } spAppResourceList.add(appResDir); spAppResourceHash.put(DISCPLINEDIR, appResDir); //--------------------------------------------------------- // Common Views //--------------------------------------------------------- title = getResourceString(L10N + "" + COMMONDIR); appResDir = getAppResDir(session, user, null, null, COMMONDIR, false, title, true); //System.out.println("COMMONDIR Dir: "+appResDir.getId()+", UT: "+appResDir.getUserType()+", IsPers: "+appResDir.getIsPersonal()+", Disp: "+appResDir.getDisciplineType()); dir = XMLHelper.getConfigDir("common"); //$NON-NLS-1$ if (dir.exists()) { mergeAppResourceDirFromDiskDir(COMMONDIR, appResDir, COMMONDIR, dir); appResDir.setUserType(COMMONDIR); } spAppResourceList.add(appResDir); spAppResourceHash.put(COMMONDIR, appResDir); //--------------------------------------------------------- // BackStop //--------------------------------------------------------- String backStopStr = "backstop"; dir = XMLHelper.getConfigDir(backStopStr); //$NON-NLS-1$ if (dir.exists()) { appResDir = createAppResourceDefFromDir(BACKSTOPDIR, dir); //$NON-NLS-1$ //System.out.println("appResDir Dir: "+appResDir.getId()+", UT: "+appResDir.getUserType()+", IsPers: "+appResDir.getIsPersonal()+", Disp: "+appResDir.getDisciplineType()); appResDir.setUserType(BACKSTOPDIR); //$NON-NLS-1$ appResDir.setTitle(getResourceString(L10N + "" + BACKSTOPDIR)); //$NON-NLS-1$ spAppResourceList.add(appResDir); spAppResourceHash.put(BACKSTOPDIR, appResDir); } if (isFirstTime) { SpecifyAppPrefs.initialPrefs(); } closeSession(); session = null; if (isFirstTime) { FixDBAfterLogin.fixDefaultDates(); // Reset the form system because // 'fixDefaultDates' loads all the forms. FormDevHelper.clearErrors(); viewSetHash.clear(); lastLoadTime = 0; // Now notify everyone if (prevDisciplineId != -1) { CommandDispatcher.dispatch(new CommandAction("Discipline", "Changed")); //$NON-NLS-1$ //$NON-NLS-2$ } if (prevCollectionId != -1) { CommandDispatcher.dispatch(new CommandAction("Collection", "Changed")); //$NON-NLS-1$ //$NON-NLS-2$ } } // We must check here before we load the schema checkForInitialFormats(); session = openSession(); // Now load the Schema, but make sure the Discipline has a localization. // for the current locale. // // Bug Fix 9167 - 04/01/2013 - Must always redo the Schema because any formatters at the collection level // otherwise will not get set // if (UIFieldFormatterMgr.isInitialized()) { UIFieldFormatterMgr.getInstance().shutdown(); UIFieldFormatterMgr.getInstance().reset(); } int disciplineId = getClassObject(Discipline.class).getDisciplineId(); if (disciplineId != prevDisciplineId) { Locale engLocale = null; Locale fndLocale = null; Locale currLocale = SchemaI18NService.getCurrentLocale(); List<Locale> locales = SchemaI18NService.getInstance() .getLocalesFromData(SpLocaleContainer.CORE_SCHEMA, disciplineId); for (Locale locale : locales) { if (locale.equals(currLocale)) { fndLocale = currLocale; } if (locale.getLanguage().equals("en")) { engLocale = currLocale; } } if (fndLocale == null) { if (engLocale != null) { fndLocale = engLocale; } else if (locales.size() > 0) { fndLocale = locales.get(0); } else { currentStatus = CONTEXT_STATUS.Error; String msg = "Specify was unable to a Locale in the Schema Config for this discipline.\nPlease contact Specify support immediately."; UIRegistry.showError(msg); AppPreferences.shutdownAllPrefs(); DataProviderFactory.getInstance().shutdown(); DBConnection.shutdown(); System.exit(0); return currentStatus; } fndLocale = engLocale != null ? engLocale : locales.get(0); SchemaI18NService.setCurrentLocale(fndLocale); Locale.setDefault(fndLocale); UIRegistry.displayErrorDlgLocalized(L10N + "NO_LOCALE", discipline.getName(), currLocale.getDisplayName(), fndLocale.getDisplayName()); } SchemaI18NService.getInstance().loadWithLocale(SpLocaleContainer.CORE_SCHEMA, disciplineId, DBTableIdMgr.getInstance(), Locale.getDefault()); } //setUpCatNumAccessionFormatters(getClassObject(Institution.class), collection); // We close the session here so all SpAppResourceDir get unattached to hibernate // because UIFieldFormatterMgr and loading views all need a session // and we don't want to reuse it and get a double session closeSession(); session = null; if (isFirstTime) { for (DBTableInfo ti : DBTableIdMgr.getInstance().getTables()) { ti.setPermissions(SecurityMgr.getInstance().getPermission("DO." + ti.getName().toLowerCase())); } // Here is where you turn on View/Viewdef re-use. /*if (true) { boolean cacheDoVerify = ViewLoader.isDoFieldVerification(); ViewLoader.setDoFieldVerification(false); UIFieldFormatterMgr.getInstance(); ViewLoader.setDoFieldVerification(cacheDoVerify); }*/ RegisterSpecify.register(false, 0); } return currentStatus = CONTEXT_STATUS.OK; } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifyAppContextMgr.class, ex); ex.printStackTrace(); } finally { if (session != null) { closeSession(); } } showLocalizedError(L10N + "CRITICAL_LOGIN_ERR"); //$NON-NLS-1$ System.exit(0); return null; }
From source file:org.opencms.frontend.templateone.form.CmsSelectWidgetXmlcontentType.java
/** * Returns the list of configured select options, parsing the configuration String if required. * <p>/*from ww w. j a v a 2 s . c om*/ * * @param cms the current users OpenCms context * @param widgetDialog the dialog of this widget * @param param the widget parameter of this dialog * * @see org.opencms.widgets.A_CmsSelectWidget#parseSelectOptions(org.opencms.file.CmsObject, * org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter) * * @return the list of configured select options. * * @throws CmsIllegalArgumentException if the "folder" property of the configuration does not denote a folder within the VFS */ protected List parseSelectOptions(CmsObject cms, I_CmsWidgetDialog widgetDialog, I_CmsWidgetParameter param) throws CmsIllegalArgumentException { Locale dialogContentLocale = ((I_CmsXmlContentValue) param).getLocale(); Locale resourceLocale; if (m_macroCmsObject == null) { try { m_macroCmsObject = OpenCms.initCmsObject(cms); m_macroCmsObject.getRequestContext().setSiteRoot("/"); } catch (CmsException e) { // should never happen if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.ERR_SELECTWIDGET_INTERNAL_CONFIGURATION_2, new Object[] { getClass().getName(), getConfiguration() })); } return Collections.EMPTY_LIST; } } if (m_macroResolver == null) { m_macroResolver = new CmsMacroResolver(); m_macroResolver.setCmsObject(m_macroCmsObject); m_macroResolver.setKeepEmptyMacros(true); } List selectOptions = getSelectOptions(); if (selectOptions == null) { String configuration = getConfiguration(); if (configuration == null) { // workaround: use the default value to parse the options configuration = param.getDefault(cms); } try { // parse configuration to members parseConfigurationInternal(configuration, cms, param); // build the set of sorted options SortedSet sortOptions = new TreeSet( new CmsResourceSelectWidgetOptionComparator(m_macroCmsObject, m_sortMacro)); CmsSelectWidgetOption option; List resources; // collect all subresources of resource folder CmsResourceFilter filter = CmsResourceFilter.DEFAULT.addRequireType(getResourceTypeID()); CmsRequestContext context = cms.getRequestContext(); String oldSiteroot = context.getSiteRoot(); context.setSiteRoot("/"); resources = cms.readResources(m_resourceFolder.getRootPath(), filter, true); context.setSiteRoot(oldSiteroot); if (resources.size() == 0) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.LOG_ERR_SELECTWIDGET_NO_RESOURCES_FOUND_3, configuration, m_resourceFolder.getRootPath(), OpenCms.getResourceManager().getResourceType(getResourceTypeID()).getTypeName())); } } Iterator itResources = resources.iterator(); CmsResource resource; String displayName; // inner loop vars : while (itResources.hasNext()) { resource = (CmsResource) itResources.next(); // don't make resources selectable that have a different locale than the current editor language. // we read the locale node of the xmlcontent instance matching the resources // locale property (or top level locale). resourceLocale = CmsLocaleManager.getLocale(cms .readPropertyObject(resource, CmsPropertyDefinition.PROPERTY_LOCALE, true).getValue()); // Only show select options for resources that are in the same locale as the current // editor locale (e.g. when switching to german, offer the german siblings) if (dialogContentLocale.equals(resourceLocale)) { // macro resolvation within hasFilterProperty will resolve values to the // current request if (hasFilterProperty(resource, cms)) { // implant the uri to the special cms object for resolving macros from // the collected xml contents: m_macroCmsObject.getRequestContext().setUri(resource.getRootPath()); // implant the resource for macro "%(opencms.filename)" m_macroResolver.setResourceName(resource.getName()); // implant the messages m_macroResolver.setMessages(widgetDialog.getMessages()); // filter out unwanted resources - if no filter properties are defined, // every resource collected here is ok: displayName = m_macroResolver.resolveMacros(getDisplayOptionMacro()); // deal with a bug of the macro resolver: it will return "" if it gets // "%(unknown.thing)": if (CmsStringUtil.isEmptyOrWhitespaceOnly(displayName)) { // it was a "%(xpath.field)" expression only and swallowed by macro // resolver: displayName = resolveXpathMacros(cms, resource, getDisplayOptionMacro()); } else { // there was more than one xpath macro: allow further replacements // within partly resolved macro: displayName = resolveXpathMacros(cms, resource, displayName); } // final check: if (CmsStringUtil.isEmpty(displayName)) { displayName = resource.getName(); } displayName = resolveXpathMacros(cms, resource, displayName); if (!CmsStringUtil.isEmpty(displayName)) { // now everything required is there: option = new CmsResourceSelectWidgetOption(resource, false, displayName); sortOptions.add(option); } } } } selectOptions = new LinkedList(sortOptions); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.ERR_SELECTWIDGET_CONFIGURATION_2, getClass(), configuration), e); } } if ((selectOptions == Collections.EMPTY_LIST) || (selectOptions == null)) { selectOptions = new ArrayList(); } // no method to add the parsed option list.... // Caution: if it is decided to return a copy of the list we are doomed unless // setSelectOptions is set to protected! List pOptions = getSelectOptions(); if (pOptions != null) { pOptions.clear(); } Iterator it = selectOptions.iterator(); while (it.hasNext()) { addSelectOption((CmsSelectWidgetOption) it.next()); } } return selectOptions; }
From source file:org.jahia.services.content.JCRNodeWrapperImpl.java
private JCRPropertyWrapper internalGetProperty(String name, ExtendedPropertyDefinition epd) throws RepositoryException { final Locale locale = getSession().getLocale(); if (epd == null) { epd = getApplicablePropertyDefinition(name); }/*from w ww . ja v a2 s .c o m*/ if (epd == null) { throw new PathNotFoundException(name); } if (locale != null) { if (epd.isInternationalized()) { Pattern pathPattern = JCRContentUtils.getInstance().getHandleFallbackLocaleForPathPattern(); if (pathPattern == null || locale.equals(SettingsBean.getInstance().getDefaultLocale())) { try { final Node localizedNode = getI18N(locale); return new JCRPropertyWrapperImpl(this, localizedNode.getProperty(name), session, provider, epd, name); } catch (ItemNotFoundException e) { return new JCRPropertyWrapperImpl(this, objectNode.getProperty(name), session, provider, epd); } } else { return internalGetPropertyI18nWithDefFallback(name, epd, locale, pathPattern); } } } return new JCRPropertyWrapperImpl(this, objectNode.getProperty(name), session, provider, epd); }
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 . j av a 2s . com 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:com.alkacon.opencms.formgenerator.CmsSelectWidgetXmlcontentType.java
/** * Returns the list of configured select options, parsing the configuration String if required. * <p>//from w ww . j av a2s. c o m * * @param cms * the current users OpenCms context. * * @param widgetDialog * the dialog of this widget. * * @param param * the widget parameter of this dialog. * * @see org.opencms.widgets.A_CmsSelectWidget#parseSelectOptions(org.opencms.file.CmsObject, * org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter) * * @return the list of configured select options. * * @throws CmsIllegalArgumentException * if the "folder" property of the configuration does not denote a folder within the VFS. */ @Override protected List parseSelectOptions(CmsObject cms, I_CmsWidgetDialog widgetDialog, I_CmsWidgetParameter param) throws CmsIllegalArgumentException { Locale dialogContentLocale = ((I_CmsXmlContentValue) param).getLocale(); Locale resourceLocale; if (m_macroCmsObject == null) { try { m_macroCmsObject = OpenCms.initCmsObject(cms); m_macroCmsObject.getRequestContext().setSiteRoot("/"); } catch (CmsException e) { // should never happen if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.ERR_SELECTWIDGET_INTERNAL_CONFIGURATION_2, new Object[] { getClass().getName(), getConfiguration() })); } return Collections.EMPTY_LIST; } } if (m_macroResolver == null) { m_macroResolver = new CmsMacroResolver(); m_macroResolver.setCmsObject(m_macroCmsObject); m_macroResolver.setKeepEmptyMacros(true); } List selectOptions = getSelectOptions(); if (selectOptions == null) { String configuration = getConfiguration(); if (configuration == null) { // workaround: use the default value to parse the options configuration = param.getDefault(cms); } try { // parse configuration to members parseConfigurationInternal(configuration, cms, param); // build the set of sorted options List<CmsResourceSelectWidgetOption> sortOptions = new ArrayList<CmsResourceSelectWidgetOption>(); CmsResourceSelectWidgetOption option; List<CmsResource> resources; List<CmsResource> allResources = new LinkedList<CmsResource>(); // collect all subresources of resource folder. // As a CmsResourceFilter is somewhat limited we have to do several reads // for each resourceType we allow: int resType; Iterator<Integer> itResTypes = this.m_resourceTypeIDs.iterator(); while (itResTypes.hasNext()) { resType = (itResTypes.next()).intValue(); CmsResourceFilter filter = CmsResourceFilter.ALL.addRequireType(resType); CmsRequestContext context = cms.getRequestContext(); String oldSiteroot = context.getSiteRoot(); context.setSiteRoot("/"); resources = cms.readResources(m_resourceFolder.getRootPath(), filter, true); context.setSiteRoot(oldSiteroot); if (resources.size() == 0) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key( Messages.LOG_ERR_SELECTWIDGET_NO_RESOURCES_FOUND_3, configuration, m_resourceFolder.getRootPath(), OpenCms.getResourceManager().getResourceType(resType).getTypeName())); } } else { allResources.addAll(resources); } } Iterator<CmsResource> itResources = allResources.iterator(); CmsResource resource; String displayName; // inner loop vars : while (itResources.hasNext()) { resource = itResources.next(); // don't make resources selectable that have a different locale than the // we read the locale node of the xmlcontent instance matching the resources // locale property (or top level locale). CmsProperty resourceLocaleProperty = cms.readPropertyObject(resource, CmsPropertyDefinition.PROPERTY_LOCALE, true); resourceLocale = OpenCms.getLocaleManager().getDefaultLocale(cms, cms.getSitePath(resource)); // We allow all resources without locale property and only the // resources with locale property that match the current XML content editor locale. if (isIgnoreLocaleMatching() || ((resourceLocaleProperty.isNullProperty() && containsLocale(cms, resource, dialogContentLocale)) || dialogContentLocale.equals(resourceLocale))) { // macro resolvation within hasFilterProperty will resolve values to the // current request if (hasFilterProperty(resource, cms)) { // implant the uri to the special cms object for resolving macros from // the collected xml contents: m_macroCmsObject.getRequestContext().setUri(resource.getRootPath()); // implant the resource for macro "%(opencms.filename)" m_macroResolver.setResourceName(resource.getName()); // implant the messages m_macroResolver.setMessages(widgetDialog.getMessages()); // filter out unwanted resources - if no filter properties are defined, // every // resource collected here is ok: displayName = m_macroResolver.resolveMacros(getDisplayOptionMacro()); // deal with a bug of the macro resolver: it will return "" if it gets // "%(unknown.thin)": if (CmsStringUtil.isEmptyOrWhitespaceOnly(displayName)) { // it was a "%(xpath.field})" expression only and swallowed by macro // resolver: displayName = resolveXpathMacros(cms, resource, getDisplayOptionMacro()); } else { // there was more than one xpath macro: allow further replacements // within partly resolved macro: displayName = resolveXpathMacros(cms, resource, displayName); } // final check: if (CmsStringUtil.isEmpty(displayName)) { displayName = resource.getName(); } displayName = resolveXpathMacros(cms, resource, displayName); if (!CmsStringUtil.isEmpty(displayName)) { // now everything required is there: option = new CmsResourceSelectWidgetOption(cms, resource, false, displayName); sortOptions.add(option); } } } } selectOptions = new LinkedList<CmsResourceSelectWidgetOption>(sortOptions); // sort the found resources according to their file name (without path information) Collections.sort(selectOptions, new CmsResourceSelectWidgetOptionComparator(m_macroCmsObject, m_sortMacro)); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.ERR_SELECTWIDGET_CONFIGURATION_2, getClass(), configuration), e); } } if ((selectOptions == null) || (selectOptions == Collections.EMPTY_LIST)) { selectOptions = new ArrayList<CmsResourceSelectWidgetOption>(); } // no method to add the parsed option list.... // Caution: if it is decided to return a copy of the list we are doomed unless // setSelectOptions is set to protected! List pOptions = getSelectOptions(); if (pOptions != null) { pOptions.clear(); } Iterator<CmsResourceSelectWidgetOption> it = selectOptions.iterator(); while (it.hasNext()) { addSelectOption(it.next()); } } return selectOptions; }
From source file:com.alkacon.opencms.v8.formgenerator.CmsSelectWidgetXmlcontentType.java
/** * Returns the list of configured select options, parsing the configuration String if required.<p> * /*from w w w. ja v a 2 s. c om*/ * @param cms the current users OpenCms context. * @param contentResource the edited resource * @param contentLocale the content locale * @param widgetDialog the dialog of this widget. * @param param the widget parameter of this dialog. * * @see org.opencms.widgets.A_CmsSelectWidget#parseSelectOptions(org.opencms.file.CmsObject, * org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter) * * @return the list of configured select options. * * @throws CmsIllegalArgumentException if the "folder" property of the configuration does not denote a folder within the VFS. */ protected List<CmsSelectWidgetOption> parseSelectOptions(CmsObject cms, CmsResource contentResource, Locale contentLocale, I_CmsWidgetDialog widgetDialog, I_CmsWidgetParameter param) throws CmsIllegalArgumentException { if (contentLocale == null) { contentLocale = ((I_CmsXmlContentValue) param).getLocale(); } if (m_macroCmsObject == null) { try { m_macroCmsObject = OpenCms.initCmsObject(cms); m_macroCmsObject.getRequestContext().setSiteRoot("/"); } catch (CmsException e) { // should never happen if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.ERR_SELECTWIDGET_INTERNAL_CONFIGURATION_2, new Object[] { getClass().getName(), getConfiguration() })); } return Collections.emptyList(); } } if (m_macroResolver == null) { m_macroResolver = new CmsMacroResolver(); m_macroResolver.setCmsObject(m_macroCmsObject); m_macroResolver.setKeepEmptyMacros(true); } List<CmsSelectWidgetOption> selectOptions = getSelectOptions(); if (selectOptions == null) { String configuration = getConfiguration(); if (configuration == null) { // workaround: use the default value to parse the options configuration = param.getDefault(cms); } List<CmsResourceSelectWidgetOption> resourceOptions = null; try { // parse configuration to members if (contentResource == null) { contentResource = ((I_CmsXmlContentValue) param).getDocument().getFile(); } parseConfigurationInternal(configuration, cms, contentResource, param); // build the set of sorted options List<CmsResourceSelectWidgetOption> sortOptions = new ArrayList<CmsResourceSelectWidgetOption>(); CmsResourceSelectWidgetOption option; List<CmsResource> resources; List<CmsResource> allResources = new LinkedList<CmsResource>(); // collect all subresources of resource folder. // As a CmsResourceFilter is somewhat limited we have to do several reads // for each resourceType we allow: int resType; Iterator<Integer> itResTypes = this.m_resourceTypeIDs.iterator(); while (itResTypes.hasNext()) { resType = (itResTypes.next()).intValue(); CmsResourceFilter filter = CmsResourceFilter.ALL.addRequireType(resType); CmsRequestContext context = cms.getRequestContext(); String oldSiteroot = context.getSiteRoot(); context.setSiteRoot("/"); resources = cms.readResources(m_resourceFolder.getRootPath(), filter, true); context.setSiteRoot(oldSiteroot); if (resources.size() == 0) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key( Messages.LOG_ERR_SELECTWIDGET_NO_RESOURCES_FOUND_3, configuration, m_resourceFolder.getRootPath(), OpenCms.getResourceManager().getResourceType(resType).getTypeName())); } } else { allResources.addAll(resources); } } Iterator<CmsResource> itResources = allResources.iterator(); CmsResource resource; String displayName; // inner loop vars : while (itResources.hasNext()) { resource = itResources.next(); // don't make resources selectable that have a different locale than the // we read the locale node of the xmlcontent instance matching the resources // locale property (or top level locale). CmsProperty resourceLocaleProperty = cms.readPropertyObject(resource, CmsPropertyDefinition.PROPERTY_LOCALE, true); Locale resourceLocale = OpenCms.getLocaleManager().getDefaultLocale(cms, cms.getSitePath(resource)); // We allow all resources without locale property and only the // resources with locale property that match the current XML content editor locale. if (isIgnoreLocaleMatching() || ((resourceLocaleProperty.isNullProperty() && containsLocale(cms, resource, contentLocale)) || contentLocale.equals(resourceLocale))) { // macro resolvation within hasFilterProperty will resolve values to the // current request if (hasFilterProperty(resource, cms)) { // implant the uri to the special cms object for resolving macros from // the collected xml contents: m_macroCmsObject.getRequestContext().setUri(resource.getRootPath()); // implant the resource for macro "%(opencms.filename)" m_macroResolver.setResourceName(resource.getName()); // implant the messages m_macroResolver.setMessages(widgetDialog.getMessages()); // filter out unwanted resources - if no filter properties are defined, // every // resource collected here is ok: displayName = m_macroResolver.resolveMacros(getDisplayOptionMacro()); // deal with a bug of the macro resolver: it will return "" if it gets // "%(unknown.thin)": if (CmsStringUtil.isEmptyOrWhitespaceOnly(displayName)) { // it was a "%(xpath.field})" expression only and swallowed by macro // resolver: displayName = resolveXpathMacros(cms, resource, getDisplayOptionMacro()); } else { // there was more than one xpath macro: allow further replacements // within partly resolved macro: displayName = resolveXpathMacros(cms, resource, displayName); } // final check: if (CmsStringUtil.isEmpty(displayName)) { displayName = resource.getName(); } displayName = resolveXpathMacros(cms, resource, displayName); if (!CmsStringUtil.isEmpty(displayName)) { // now everything required is there: option = new CmsResourceSelectWidgetOption(cms, resource, false, displayName); sortOptions.add(option); } } } } resourceOptions = new LinkedList<CmsResourceSelectWidgetOption>(sortOptions); // sort the found resources according to their file name (without path information) Collections.sort(resourceOptions, new CmsResourceSelectWidgetOptionComparator(m_macroCmsObject, m_sortMacro)); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.ERR_SELECTWIDGET_CONFIGURATION_2, getClass(), configuration), e); } } if (resourceOptions == null) { resourceOptions = Collections.emptyList(); } Iterator<CmsResourceSelectWidgetOption> it = resourceOptions.iterator(); while (it.hasNext()) { addSelectOption(it.next()); } selectOptions = getSelectOptions(); } return selectOptions; }
From source file:com.globalsight.webservices.Ambassador.java
/** * Exports the job. If p_workflowLocale is null then all pages for all * workflows are exported, otherwise the specific workflow corresponding to * the locale is exported./* w ww.j av a 2 s .c o m*/ * * @param p_jobName * -- name of job * @param p_workflowLocale * -- locale of workflow to export * @return String * @exception WebServiceException */ public String exportWorkflow(String p_accessToken, String p_jobName, String p_workflowLocale) throws WebServiceException { checkAccess(p_accessToken, EXPORT_WORKFLOW); checkPermission(p_accessToken, Permission.JOB_WORKFLOWS_EXPORT); String jobName = p_jobName; String workflowLocale = p_workflowLocale; String returnXml = ""; WebServicesLog.Start activityStart = null; try { String userName = getUsernameFromSession(p_accessToken); Map<Object, Object> activityArgs = new HashMap<Object, Object>(); activityArgs.put("loggedUserName", userName); activityArgs.put("jobName", p_jobName); activityArgs.put("workflowLocale", p_workflowLocale); activityStart = WebServicesLog.start(Ambassador.class, "exportWorkflow(p_accessToken, p_jobName,p_workflowLocale)", activityArgs); StringBuffer xml = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n"); Job job = queryJob(jobName, p_accessToken); Object[] workflows = job.getWorkflows().toArray(); long projectId = job.getL10nProfile().getProject().getId(); User projectMgr = ServerProxy.getProjectHandler().getProjectById(projectId).getProjectManager(); boolean didExport = false; if (workflowLocale == null) { // export all workflow logger.info("Exporting all " + workflows.length + " workflows for job " + jobName); for (int i = 0; i < workflows.length; i++) { Workflow w = (Workflow) workflows[i]; if (!w.getState().equals(Workflow.IMPORT_FAILED) && !w.getState().equals(Workflow.CANCELLED)) { exportSingleWorkflow(job, w, projectMgr); } } didExport = true; } else { // export just one workflow Locale locale = GlobalSightLocale.makeLocaleFromString(workflowLocale); logger.info("Job " + jobName + " has " + workflows.length + " workflow."); for (int i = 0; i < workflows.length; i++) { Workflow w = (Workflow) workflows[i]; Locale wLocale = w.getTargetLocale().getLocale(); if (locale.equals(wLocale)) { exportSingleWorkflow(job, w, projectMgr); didExport = true; break; } } } if (didExport == false) throw new Exception("No workflow for locale " + workflowLocale); xml.append("<exportStatus>\r\n"); xml.append("\t<jobName>").append(EditUtil.encodeXmlEntities(jobName)).append("</jobName>\r\n"); if (workflowLocale == null) xml.append("\t<workflowLocale>All Locales</workflowLocale>\r\n"); else xml.append("\t<workflowLocale>").append(workflowLocale).append("</workflowLocale>\r\n"); xml.append("\t<status>Export Request Sent</status>\r\n"); xml.append("</exportStatus>\r\n"); returnXml = xml.toString(); } catch (Exception e) { logger.error("exportWorkflow()", e); String message = "Could not export workflow for job " + jobName; message = makeErrorXml("exportWorkflow", message); throw new WebServiceException(message); } finally { if (activityStart != null) { activityStart.end(); } } return returnXml; }
From source file:com.globalsight.webservices.Ambassador.java
/** * Cancels the job. If p_workflowLocale is null then all workflows are * canceled, otherwise the specific workflow corresponding to the locale is * canceled.//from w w w.j a va 2s .c o m * * @param p_jobName * -- name of job * @param p_workflowLocale * -- locale of workflow to cancel * @return String * @exception WebServiceException */ public String cancelWorkflow(String p_accessToken, String p_jobName, String p_workflowLocale) throws WebServiceException { checkAccess(p_accessToken, CANCEL_WORKFLOW); checkPermission(p_accessToken, Permission.JOB_WORKFLOWS_DISCARD); WebServicesLog.Start activityStart = null; String jobName = p_jobName; String workflowLocale = p_workflowLocale; try { String userName = getUsernameFromSession(p_accessToken); Map<Object, Object> activityArgs = new HashMap<Object, Object>(); activityArgs.put("loggedUserName", userName); activityArgs.put("jobName", p_jobName); activityArgs.put("workflowLocale", p_workflowLocale); activityStart = WebServicesLog.start(Ambassador.class, "cancelWorkflow(p_accessToken, p_jobName,p_workflowLocale)", activityArgs); StringBuffer xml = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n"); Job job = queryJob(jobName, p_accessToken); String status = job.getState(); boolean didCancel = false; String userId = UserUtil.getUserIdByName(userName); if (workflowLocale == null) { // cancel the whole job logger.info("Cancelling all workflows for job " + jobName); ServerProxy.getJobHandler().cancelJob(userId, job, null); didCancel = true; } else { if (!status.equals(Job.DISPATCHED) && !status.equals(Job.READY_TO_BE_DISPATCHED)) throw new WebServiceException( "You can only discard workflows that are in the following states:DISPATCHED or READY_TO_BE_DISPATCHED"); // cancel just one workflow Locale locale = GlobalSightLocale.makeLocaleFromString(workflowLocale); Object[] workflows = job.getWorkflows().toArray(); logger.info("Job " + jobName + " has " + workflows.length + " workflow."); for (int i = 0; i < workflows.length; i++) { Workflow w = (Workflow) workflows[i]; Locale wLocale = w.getTargetLocale().getLocale(); if (locale.equals(wLocale)) { logger.info("Cancelling workflow " + workflowLocale + " for job " + jobName); ServerProxy.getWorkflowManager().cancel(userId, w); didCancel = true; break; } } } if (didCancel == false) throw new Exception("No workflow for locale " + workflowLocale); xml.append("<cancelStatus>\r\n"); xml.append("\t<jobName>").append(EditUtil.encodeXmlEntities(jobName)).append("</jobName>\r\n"); if (workflowLocale == null) xml.append("\t<workflowLocale>All Locales</workflowLocale>\r\n"); else xml.append("\t<workflowLocale>").append(workflowLocale).append("</workflowLocale>\r\n"); xml.append("\t<status>canceled</status>\r\n"); xml.append("</cancelStatus>\r\n"); return xml.toString(); } catch (Exception e) { logger.error("cancelWorkflow()", e); String message = "Could not cancel workflow for job " + jobName; message = makeErrorXml("cancelWorkflow", message); throw new WebServiceException(message); } finally { if (activityStart != null) { activityStart.end(); } } }