List of usage examples for java.util Locale getCountry
public String getCountry()
From source file:org.sakaiproject.yaft.tool.YaftTool.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (logger.isDebugEnabled()) { logger.debug("doGet()"); }//from w w w . j a va2 s.c o m if (yaftForumService == null || sakaiProxy == null) throw new ServletException("yaftForumService and sakaiProxy MUST be initialised."); String userId = null; Session session = (Session) request.getAttribute(RequestFilter.ATTR_SESSION); if (session != null) { userId = session.getUserId(); } else { // We are not logged in throw new ServletException("getCurrentUser returned null."); } ResourceLoader rl = new ResourceLoader(userId, "org.sakaiproject.yaft.tool.bundle.ui"); Locale locale = rl.getLocale(); String language = locale.getLanguage(); String country = locale.getCountry(); String isoLanguage = language; if (country != null && !country.equals("")) { isoLanguage += "_" + country; } // These go in a separate variable String[] months = rl.getString("months").split(","); String sakaiHtmlHead = (String) request.getAttribute("sakai.html.head"); request.setAttribute("sakaiHtmlHead", sakaiHtmlHead); request.setAttribute("userId", userId); String siteId = sakaiProxy.getCurrentSiteId(); request.setAttribute("siteId", siteId); request.setAttribute("state", "forums"); String placementId = (String) request.getAttribute(Tool.PLACEMENT_ID); request.setAttribute("placementId", placementId); request.setAttribute("isoLanguage", isoLanguage); request.setAttribute("editor", sakaiProxy.getWysiwygEditor()); request.setAttribute("i18n", rl); request.setAttribute("months", months); String pathInfo = request.getPathInfo(); String uri = request.getRequestURI(); if (uri.contains("/portal/pda/")) { request.setAttribute("viewMode", "minimal"); request.setAttribute("onPDAPortal", "true"); } else { request.setAttribute("viewMode", "full"); request.setAttribute("onPDAPortal", "false"); } if (pathInfo == null || pathInfo.length() < 1) { response.setContentType("text/html"); request.getRequestDispatcher("/WEB-INF/bootstrap.jsp").include(request, response); } else { String[] parts = pathInfo.substring(1).split("/"); if (parts.length >= 1) { String part1 = parts[0]; if (part1.startsWith("forums")) { doForumsGet(request, response, parts, userId, siteId, placementId, locale); } else if ("authors".equals(part1)) { if (parts.length == 1) { List<Author> authors = yaftForumService.getAuthorsForCurrentSite(); JSONArray data = JSONArray.fromObject(authors); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("application/json; charset=UTF-8"); response.getWriter().write(data.toString()); return; } else if (parts.length == 3) { String authorId = parts[1]; String authorOp = parts[2]; if ("messages".equals(authorOp)) { List<Message> messages = yaftForumService.getMessagesForAuthorInCurrentSite(authorId); JsonConfig config = new JsonConfig(); config.setExcludes(new String[] { "properties", "reference" }); JSONArray data = JSONArray.fromObject(messages, config); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("application/json; charset=UTF-8"); response.getWriter().write(data.toString()); return; } } } else if ("siteGroups".equals(part1)) { List<Group> groups = sakaiProxy.getCurrentSiteGroups(); JSONArray data = JSONArray.fromObject(groups); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("application/json; charset=UTF-8"); response.getWriter().write(data.toString()); return; } else if ("assignments".equals(part1)) { doAssignmentsGet(response, parts); } else if ("perms.json".equals(part1)) { doPermsGet(response); } else if ("userData.json".equals(part1)) { doUserDataGet(response, siteId); } else if ("forumContainingMessage".equals(part1)) { String messageId = (String) request.getParameter("messageId"); if (messageId == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid path provided: expect to receive the message id"); return; } Message message = yaftForumService.getMessage(messageId); if (message == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid messageId provided."); return; } Forum forum = yaftForumService.getForumContainingMessage(messageId); JSONObject data = JSONObject.fromObject(forum); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("application/json; charset=UTF-8"); response.getWriter().write(data.toString()); return; } else if ("discussions".equals(part1)) { doDiscussionsGet(request, response, parts, userId, siteId, placementId, locale); } else if ("messages".equals(part1)) { doMessagesGet(request, response, parts, userId, siteId, placementId, locale); } } } }
From source file:org.rti.zcore.dar.struts.action.FormDisplayAction.java
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { /*if (SystemStateManager.getCurrentState() != SystemStateManager.STATUS_NORMAL) { return mapping.findForward(LOCKED_FORWARD); }*//*from w ww.j a v a 2 s . com*/ HttpSession session = request.getSession(); Principal user = request.getUserPrincipal(); Locale locale = getLocale(request); Locale sessionLocale = (Locale) request.getAttribute("sessionLocale"); String sessionLocaleString = null; if ((sessionLocale.getLanguage() != null) && ((sessionLocale.getCountry() != null) && (!sessionLocale.getCountry().equals("")))) { sessionLocaleString = sessionLocale.getLanguage() + "_" + sessionLocale.getCountry(); } else if (sessionLocale.getLanguage() != null) { sessionLocaleString = sessionLocale.getLanguage(); } String username = user.getName(); Connection conn = null; Form encounterForm; BaseEncounter encounter = null; Map encMap = null; try { conn = DatabaseUtils.getZEPRSConnection(username); String formName = null; String encounterIdString = ""; if (mapping.getParameter() != null && !mapping.getParameter().equals("")) { formName = mapping.getParameter(); if (request.getAttribute("encounterId") != null) { encounterIdString = request.getAttribute("encounterId").toString(); } } else { formName = request.getAttribute("id").toString(); } // Sometimes encounterId is sent in url if (request.getParameter("encounterId") != null) { encounterIdString = request.getParameter("encounterId").toString(); } DarSessionSubject sessionPatient = null; Long patientId = null; //Long eventId = null; String eventUuid = null; if (request.getParameter("next") != null) { String next = request.getParameter("next"); request.setAttribute("next", next); } String fixName = StringManipulation.fixClassname(formName); Long formId = (Long) DynaSiteObjects.getFormNameMap().get(fixName); encounterForm = ((Form) DynaSiteObjects.getForms().get(new Long(formId))); String siteId = ""; try { siteId = SessionUtil.getInstance(session).getClientSettings().getSiteId().toString(); } catch (SessionUtil.AttributeNotFoundException e) { // it's ok - we're in admin mode. } if (!formName.equals("PatientRegistration") && !formName.equals("PerpetratorDemographics") && encounterForm.getFormTypeId() != 5) { try { sessionPatient = (DarSessionSubject) SessionUtil.getInstance(session).getSessionPatient(); patientId = sessionPatient.getId(); //eventId = sessionPatient.getCurrentEventId(); eventUuid = sessionPatient.getCurrentEventUuid(); } catch (SessionUtil.AttributeNotFoundException e) { log.error("Unable to get SessionSubject for " + formName); } } else { if (request.getParameter("patientId") != null) { patientId = Long.valueOf(request.getParameter("patientId")); try { sessionPatient = (DarSessionSubject) SessionUtil.getInstance(session).getSessionPatient(); } catch (SessionUtil.AttributeNotFoundException e) { log.error("Unable to get TimsSessionSubject"); } //eventId = sessionPatient.getCurrentEventId(); eventUuid = sessionPatient.getCurrentEventUuid(); } } HashMap visiblePageItems = new HashMap(); if (request.getParameter("id") != null) { encounterIdString = request.getParameter("id"); } boolean drugList = false; String newform = ""; if (request.getAttribute("newform") != null) { newform = (String) request.getAttribute("newform"); } // Editing a form? if (!encounterIdString.equals("")) { Long encounterId = new Long(encounterIdString); String className = Constants.getDynasiteFormsPackage() + "." + StringManipulation.fixClassname(encounterForm.getName()); Class clazz = null; try { clazz = Class.forName(className); } catch (ClassNotFoundException e) { e.printStackTrace(); } if (encounterForm.getFormTypeId() == 6) { // patient bridge table form encounter = PatientBridgeTableDAO.getEncounter(conn, encounterForm, formId, encounterId, clazz); Long encSiteId = encounter.getSiteId(); if (encSiteId != null) { Site site = (Site) DynaSiteObjects.getClinicMap().get(encSiteId); if (site != null) { encounter.setSiteName(site.getName()); } } } else { try { encounter = populateEncounterI18n(request, sessionLocale, sessionLocaleString, conn, encounterForm, formId, encounterId, clazz); encMap = PatientRecordUtils.getEncounterMap(encounterForm, encounter, "fieldId"); encounter.setEncounterMap(encMap); } catch (ObjectNotFoundException e) { String errorMessage = "<p>An error has occurred. The system was unable to retrieve the requested record. " + "Please press the \"Back\" button and try another link.</p>" + "<p>This error has been logged by the system.</p>"; String logMessage = errorMessage + "\n * Code is from FormDisplayAction." + "\n * Debug: encounterId: " + encounterId + ", class: " + clazz + "Error: " + e; log.error(logMessage); log.error(e); request.setAttribute("exception", errorMessage); return mapping.findForward("error"); } DynaValidatorForm dynaForm = (DynaValidatorForm) form; // used to store values used in multiselect tag HashMap multiValues = new HashMap(); // Section Map is used to reveal hidden fields that have values // Should reveal all values in case user needs to enter data for one of the hidden fields Map formSection = (Map) DynaSiteObjects.getFormSections().get(encounterForm.getId()); Map formDependencies = (Map) DynaSiteObjects.getFormDependencies().get(encounterForm.getId()); Map collapsingSections = (Map) DynaSiteObjects.getCollapsingSections() .get(encounterForm.getId()); Map collapsingDependencies = (Map) DynaSiteObjects.getCollapsingDependencies() .get(encounterForm.getId()); // Loop through the pageItems and use the encounterMap to identify the pageItems that have values // If it has a value, use the sectionMap to make that section visible. Long section = null; Long collapsingTableId = null; // Set newPageItems = new TreeSet(new DisplayOrderComparator()); for (Iterator iterator = encounterForm.getPageItems().iterator(); iterator.hasNext();) { PageItem pageItem = (PageItem) iterator.next(); // createPageItem(pageItem); String value = null; Long collapsingSectionId = null; if (pageItem.getForm_field().isEnabled() == true) { // Find which section the field is in try { section = (Long) formDependencies.get(pageItem.getForm_field().getId()); } catch (Exception e) { // it's ok } // Is it in a collapsingSection? try { collapsingSectionId = (Long) collapsingDependencies .get(pageItem.getForm_field().getId()); if (collapsingSectionId != null) { ArrayList collapsingSection = (ArrayList) collapsingSections .get(collapsingSectionId); //the table that is dependent upon the collapsing table if the second item in the list. collapsingTableId = (Long) collapsingSection.get(1); } // collapsingTableId = (Long) formDependencies.get(collapsingSection); } catch (Exception e) { // it's ok } String fieldName = null; FormField formField = pageItem.getForm_field(); /*Long currentId = formField.getId(); if (formField.getImportId() != null) { currentId = formField.getImportId(); } if (formField.getImportId() != null) { fieldName = "field" + currentId; } else {*/ //fieldName = StringManipulation.firstCharToLowerCase(formField.getStarSchemaName()); fieldName = formField.getIdentifier(); //} value = (String) encMap.get(fieldName); // value = BeanUtils.getProperty(encounter, "field" + pageItem.getForm_field().getId()); // Do not need to set property if it's null if (value != null) { if (!pageItem.getForm_field().getType().equals("Display")) { dynaForm.set(fieldName, value); } // Use the sectionMap to make that section visible if necessary. if ((!pageItem.isVisible()) & (section != null)) { // pageItem.setVisible(true); visiblePageItems.put("pageItem" + pageItem.getId(), "visible"); } // Use the sectionMap to make that collapsingSection visible if necessary. if (collapsingTableId != null) { visiblePageItems.put("pageItem" + collapsingTableId, "visible"); } // also set its sister fields in the section to true // loop through the formSection, matching the masterId List deps = (List) formSection.get(section); if (deps != null) { for (int i = 0; i < deps.size(); i++) { Long depId = (Long) deps.get(i); PageItem depPageItem = (PageItem) DynaSiteObjects.getPageItems().get(depId); // depPageItem.setVisible(true); visiblePageItems.put("pageItem" + pageItem.getId(), "visible"); } } } // Make all hidden fields visible if (!pageItem.isVisible()) { // pageItem.setVisible(true); visiblePageItems.put("pageItem" + pageItem.getId(), "visible"); } if (pageItem.getInputType().equals("druglist")) { drugList = true; } if (pageItem.getInputType().equals("multiselect_enum")) { List masterList = new ArrayList(); //multiValues.put(currentId, masterList); multiValues.put(fieldName, masterList); } // populate the multiHelper array // each field in which the multiselect widget stores data has the multiselect widget field id in the // visibleDependencies1 property if (pageItem.getInputType().equals("multiselect_item")) { List itemList = null; String visDeps1 = pageItem.getVisibleDependencies1(); if (visDeps1 != null) { try { itemList = (List) multiValues.get(new Long(visDeps1)); } catch (NullPointerException e) { e.printStackTrace(); // multiselect_enum not exist, or out of order. } } else { String error = "multiselect widget setup error - select the widget id for this field's visible deps1."; log.error(error); request.setAttribute("exception", error); return mapping.findForward("error"); } value = BeanUtils.getProperty(encounter, fieldName); if (value != null) { //multifields.append(value+ ","); itemList.add(value); //multiValues.put(pageItem.getVisibleDependencies1(), itemList); } } } } request.setAttribute("multiValues", multiValues); } request.setAttribute(SUBJECT_KEY, encounter); Date dateVisit = encounter.getDateVisit(); request.setAttribute("dateVisit", dateVisit); // used for remote widgets request.setAttribute("className", className); // loading of body onload DWRUtil.useLoadingMessage() request.setAttribute("dwr", 1); } else { if (sessionPatient != null && sessionPatient.getDead() != null && sessionPatient.getDead().equals(Boolean.TRUE)) { String forwardString = null; if (sessionPatient != null) { //Long flowId = sessionPatient.getCurrentFlowId(); Long flowId = encounterForm.getFlowId(); if (flowId.intValue() == 2) { forwardString = "/PatientItem/list.do"; } else { forwardString = "/patientTask.do?flowId=" + flowId.toString(); } } else { forwardString = "/home.do"; } ActionForward forwardForm = null; forwardForm = new ActionForward(forwardString); forwardForm.setRedirect(true); return forwardForm; } } if (visiblePageItems.size() > 0) { request.setAttribute("visiblePageItems", visiblePageItems); } request.setAttribute("encounterForm", encounterForm); List drugs = DynaSiteObjects.getDrugs(); request.setAttribute("drugs", drugs); List sites = DynaSiteObjects.getClinics(); request.setAttribute("sites", sites); String patientSiteId = SessionUtil.getInstance(session).getClientSettings().getSiteId().toString(); Site site = (Site) DynaSiteObjects.getClinicMap().get(new Long(patientSiteId)); Integer siteTypeId = site.getSiteTypeId(); String siteAlphaId = site.getSiteAlphaId().substring(0, 2); String clinicId = site.getSiteAlphaId().substring(2, 3); request.setAttribute("siteAlphaId", siteAlphaId); request.setAttribute("clinicId", clinicId); request.setAttribute("siteTypeId", siteTypeId); request.setAttribute("patientSiteId", patientSiteId); if ((encounterIdString.equals(""))) { // See if this form has 1 MaxSubmissions int maxSubmissions = encounterForm.getMaxSubmissions(); Boolean startNewEvent = encounterForm.getStartNewEvent(); if (maxSubmissions == 1) { if (startNewEvent != null && startNewEvent == true) { // start a new Event } else { EncounterData encounterOneOnly = null; try { encounterOneOnly = (EncounterData) EncountersDAO.getId(conn, patientId, eventUuid, new Long(formId)); Long encounterId = encounterOneOnly.getId(); ActionForward forwardForm = null; forwardForm = new ActionForward( "/viewEncounter.do?patientId=" + patientId + "&id=" + encounterId); forwardForm.setRedirect(true); return forwardForm; // send to the record view of this form. } catch (ObjectNotFoundException e1) { // it's ok - form not submitted yet. } } } // patient registration needs sex to be pre-filled to female if (encounterForm.getId().intValue() == 1) { DynaValidatorForm dynaForm = (DynaValidatorForm) form; dynaForm.set("sex", "1"); } } List yearList = DateUtils.getYearList(); request.setAttribute("yearList", yearList); // Process the dynamic dropdown lists. HashMap listMap = new HashMap(); Form inlineForm = null; for (Iterator iterator = encounterForm.getPageItems().iterator(); iterator.hasNext();) { PageItem pageItem = (PageItem) iterator.next(); FormField formField = pageItem.getForm_field(); String identifier = formField.getIdentifier(); if (pageItem.getInputType().equals("dropdown") || pageItem.getInputType().equals("dropdown-add-one") || pageItem.getInputType().equals("dropdown_site")) { List list = WidgetUtils.getList(conn, pageItem.getDropdownTable(), pageItem.getDropdownColumn(), pageItem.getDropdownConstraint(), pageItem.getDropdownOrderByClause(), DropdownItem.class, pageItem.getFkIdentifier()); // Process PatientItem later. if (!formName.equals("PatientItem")) { listMap.put(pageItem.getId(), list); } if (pageItem.getInputType().equals("dropdown-add-one")) { String classNameString = StringManipulation.fixClassname(pageItem.getDropdownTable()); Long inlineFormId = (Long) DynaSiteObjects.getFormNameMap().get(classNameString); inlineForm = ((Form) DynaSiteObjects.getForms().get(new Long(inlineFormId))); // Create a list of fieldnames for inline forms. ArrayList<String> inlineFields = new ArrayList<String>(); for (Iterator iterator2 = inlineForm.getPageItems().iterator(); iterator2.hasNext();) { PageItem pageItem2 = (PageItem) iterator2.next(); if (pageItem2.getForm_field().isEnabled() == true && !pageItem2.getForm_field().getType().equals("Display")) { inlineFields.add(pageItem2.getForm_field().getIdentifier()); } } request.setAttribute("inlineForm_" + identifier, inlineForm); request.setAttribute("inlineFields_" + identifier, inlineFields); // loading of body onload DWRUtil.useLoadingMessage() request.setAttribute("dwr", 1); } } } // For DAR/ART care form 132 if (formName.equals("PatientItem")) { // Fetch the patient's regimen. Long regimenId = sessionPatient.getRegimenId(); String regimenName = sessionPatient.getRegimenName(); List<PatientItem> items = RegimenUtils.getAllItemsForRegimen(conn, regimenId); // now construct a list of items for the dropdown. // We'll replace the one that was just created. HashMap<Long, StockReport> balanceMap = null; if (DynaSiteObjects.getStatusMap().get("balanceMap") != null) { balanceMap = (HashMap<Long, StockReport>) DynaSiteObjects.getStatusMap().get("balanceMap"); } List list = new ArrayList(); for (PatientItem regimenItem_bridge : items) { Long itemId = regimenItem_bridge.getItem_id(); DropdownItem item = null; try { item = RegimenUtils.getItemForRegimen(conn, itemId); //StockControl tempStockControl = InventoryDAO.getCurrentStockBalance(conn, itemId, Integer.valueOf(siteId)); if (balanceMap != null) { StockReport stockReport = balanceMap.get(itemId); Integer balance = 0; if (stockReport != null) { balance = stockReport.getBalanceBF(); } if (balance <= 0) { /*String value = item.getDropdownValue(); item.setDropdownValue(value + " ** Out of Stock ** Bal: " + balance);*/ } else { String value = item.getDropdownValue(); item.setDropdownValue(value + " Bal: " + balance); list.add(item); } } } catch (Exception e) { log.debug("Unable to fetch item for regimen: " + regimenName + " regimenId: " + regimenId + " itemId: " + itemId); } } if (sessionPatient.getChild() != null && sessionPatient.getChild() == true) { List<DropdownItem> paedsItems = RegimenUtils.getPaediatricSingleDrugItems(conn); for (DropdownItem dropdownItem : paedsItems) { StockReport stockReport = balanceMap.get(Long.valueOf(dropdownItem.getDropdownId())); Integer balance = 0; if (stockReport != null) { balance = stockReport.getBalanceBF(); } if (balance <= 0) { } else { String value = dropdownItem.getDropdownValue(); dropdownItem.setDropdownValue(value + " Bal: " + balance); list.add(dropdownItem); } } } List<DropdownItem> otherItems = RegimenUtils.getOtherDropdownItems(conn); for (DropdownItem dropdownItem : otherItems) { StockReport stockReport = balanceMap.get(Long.valueOf(dropdownItem.getDropdownId())); Integer balance = 0; if (stockReport != null) { balance = stockReport.getBalanceBF(); } if (balance <= 0) { } else { String value = dropdownItem.getDropdownValue(); dropdownItem.setDropdownValue(value + " Bal: " + balance); list.add(dropdownItem); } } //list.addAll(otherItems); if (list.size() > 0) { listMap.put(Long.valueOf(4376), list); } } request.setAttribute("listMap", listMap); if (encounterForm.getRecordsPerEncounter() != null && encounterForm.getRecordsPerEncounter() > 0) { if (encounterForm.getResizedForPatientBridge() == null) { FormUtils.createBridgeTablePageItems(encounterForm); } } if (sessionPatient != null && sessionPatient.getPatientType() == 2) { List<Patient> clientList = RelationshipDAO.getRelationshipToUuid2(conn, sessionPatient); request.setAttribute("relationshipList", clientList); } // Keep this block at the end - it sets sessionPatient to null in certain circumstances. // Set the tasklist for particular circumstances. First check if the form requires a patient or if "id" is in the reqiest. if ((encounterForm.isRequirePatient() || ((request.getParameter("id") != null)))) { // we don't need the tasklist if we're just editing a form or it's in unassigned flow Long unassigned = new Long("100"); if (request.getParameter("id") == null) { if (!encounterForm.getFlow().getId().equals(unassigned)) { // moved code for form 66 below. } } Boolean status = Boolean.valueOf(true); /*if (eventUuid == null) { return mapping.findForward("home"); }*/ List activeProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid, status, sessionPatient); request.setAttribute("activeProblems", activeProblems); // now get inactive problems status = Boolean.valueOf(false); List inactiveProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid, status, sessionPatient); request.setAttribute("inactiveProblems", inactiveProblems); // Display task list if editing form 1. } else if ((encounterForm.getId().intValue() == 1) & (patientId != null)) { Boolean status = Boolean.valueOf(true); List activeProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid, status, sessionPatient); request.setAttribute("activeProblems", activeProblems); // now get inactive problems status = Boolean.valueOf(false); List inactiveProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid, status, sessionPatient); request.setAttribute("inactiveProblems", inactiveProblems); } else if ((formName.equals("PerpetratorDemographics")) & (patientId != null)) { Boolean status = Boolean.valueOf(true); List activeProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid, status, sessionPatient); request.setAttribute("activeProblems", activeProblems); // now get inactive problems status = Boolean.valueOf(false); List inactiveProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid, status, sessionPatient); request.setAttribute("inactiveProblems", inactiveProblems); // otherwise reset sessionPatient } else { SessionUtil.getInstance(session).setSessionPatient(null); } } catch (ServletException e) { log.error(e); } finally { if (conn != null && !conn.isClosed()) { conn.close(); } } encounterForm = null; return mapping.findForward("success"); }
From source file:com.scoreflex.Scoreflex.java
/** * Gets the current language. If language was specified using {@link * Scoreflex.setLang(String)}, this value is returned. Otherwise it is * guessed from the system.//from ww w .j a v a 2s .c o m * * @return The locale in use. */ public static String getLang() { if (null != sLang) return sLang; Locale locale = Locale.getDefault(); if (null == locale) return DEFAULT_LANGUAGE_CODE; String language = locale.getLanguage(); String country = locale.getCountry(); String localeString = String.format("%s_%s", language != null ? language.toLowerCase(Locale.ENGLISH) : "", country != null ? country.toUpperCase(Locale.ENGLISH) : ""); // 1. if no language is specified, return the default language if (null == language) return DEFAULT_LANGUAGE_CODE; // 2. try to match the language or the entire locale string among the // list of available language codes String matchedLanguageCode = null; for (int i = 0; i < VALID_LANGUAGE_CODES.length; i++) { if (VALID_LANGUAGE_CODES[i].equals(localeString)) { // return here as this is the most precise match we can get return localeString; } if (VALID_LANGUAGE_CODES[i].equals(language)) { // set the matched language code, and continue iterating as we // may match the localeString in a later iteration. matchedLanguageCode = language; } } if (null != matchedLanguageCode) return matchedLanguageCode; return DEFAULT_LANGUAGE_CODE; }
From source file:org.openmrs.api.impl.AdministrationServiceImpl.java
/** * @see org.openmrs.api.AdministrationService#getPresentationLocales() *///from w w w . j av a 2s . co m @Transactional(readOnly = true) public Set<Locale> getPresentationLocales() { if (presentationLocales == null) { presentationLocales = new HashSet<Locale>(); Collection<Locale> messageLocales = Context.getMessageSourceService().getLocales(); List<Locale> allowedLocales = getAllowedLocales(); for (Locale locale : allowedLocales) { // if no country is specified all countries with this language will be added if (StringUtils.isEmpty(locale.getCountry())) { List<Locale> localsWithSameLanguage = new ArrayList<Locale>(); for (Locale possibleLocale : messageLocales) { if (locale.getLanguage().equals(possibleLocale.getLanguage()) && !StringUtils.isEmpty(possibleLocale.getCountry())) { localsWithSameLanguage.add(possibleLocale); } } // if there are country locales we add those only if (!localsWithSameLanguage.isEmpty()) { presentationLocales.addAll(localsWithSameLanguage); } else { // if there are no country locales we add possibleLocale which has country as "" // e.g: if 'es' locale has no country based entries es_CL etc. we show default 'es' if (messageLocales.contains(locale)) { presentationLocales.add(locale); } } } else { // if locales list contains exact <language,country> pair add it if (messageLocales.contains(locale)) { presentationLocales.add(locale); } else { // if no such entry add possibleLocale with country "" // e.g: we specify es_CL but it is not in list so we add es locale here for (Locale possibleLocale : messageLocales) { if (locale.getLanguage().equals(possibleLocale.getLanguage()) && StringUtils.isEmpty(possibleLocale.getCountry())) { presentationLocales.add(possibleLocale); } } } } } } return presentationLocales; }
From source file:org.openmrs.web.dwr.ConceptListItem.java
/** * Populate all of the attributes of this class * * @param concept// w ww . java2 s . co m * @param conceptName * @param locale */ private void initialize(Concept concept, ConceptName conceptName, Locale locale) { if (concept != null) { conceptId = concept.getConceptId(); ConceptName conceptShortName = concept.getShortNameInLocale(locale); name = ""; shortName = ""; description = ""; if (conceptName != null) { conceptNameId = conceptName.getConceptNameId(); if (conceptName.isIndexTerm() && concept.getName() == null) { name = WebUtil.escapeHTML(conceptName.getName()) + Context.getMessageSourceService().getMessage("Concept.no.fullySpecifiedName.found"); } else { name = WebUtil.escapeHTML(conceptName.getName()); } // if the name hit is not the preferred or fully specified one, put the fully specified one here if (!conceptName.isPreferred()) { ConceptName preferredNameObj = concept.getPreferredName(locale); if (preferredNameObj == null && !StringUtils.isBlank(locale.getCountry()) || !StringUtils.isBlank(locale.getVariant())) { preferredNameObj = concept.getPreferredName(new Locale(locale.getLanguage())); } if (preferredNameObj != null) { preferredName = preferredNameObj.getName(); } } } if (conceptShortName != null) { shortName = WebUtil.escapeHTML(conceptShortName.getName()); } ConceptDescription conceptDescription = concept.getDescription(locale, false); if (conceptDescription != null) { description = WebUtil.escapeHTML(conceptDescription.getDescription()); } isCodedDatatype = concept.getDatatype().isCoded(); retired = concept.isRetired(); hl7Abbreviation = concept.getDatatype().getHl7Abbreviation(); className = concept.getConceptClass().getName(); isSet = concept.isSet(); isNumeric = concept.isNumeric(); if (isNumeric) { // TODO: There's probably a better way to do this, but just doing "(ConceptNumeric) concept" throws "java.lang.ClassCastException: org.openmrs.Concept$$EnhancerByCGLIB$$85e62ac7" ConceptNumeric num = Context.getConceptService().getConceptNumeric(concept.getConceptId()); hiAbsolute = num.getHiAbsolute(); hiCritical = num.getHiCritical(); hiNormal = num.getHiNormal(); lowAbsolute = num.getLowAbsolute(); lowCritical = num.getLowCritical(); lowNormal = num.getLowNormal(); units = num.getUnits(); } } }
From source file:org.sakaiproject.cheftool.VelocityPortletPaneledAction.java
/** * Dispatch to a "do" method based on reflection. Override ToolServlet to support the old "build" ways. * /* ww w . j ava2 s . co m*/ * @param methodBase * The base name of the method to call. * @param methodExt * The end name of the method to call. * @param req * The HttpServletRequest. * @param res * The HttpServletResponse */ protected void toolModeDispatch(String methodBase, String methodExt, HttpServletRequest req, HttpServletResponse res) throws ToolException { // the context wraps our real vm attribute set Context context = (Context) req.getAttribute(ATTR_CONTEXT); // other wrappers VelocityPortlet portlet = (VelocityPortlet) req.getAttribute(ATTR_PORTLET); JetspeedRunData rundata = (JetspeedRunData) req.getAttribute(ATTR_RUNDATA); // "panel" is used to identify the specific panel in the URL context.put("param_panel", ActionURL.PARAM_PANEL); // set the "action" context.put("action", getState(req).getAttribute(STATE_ACTION)); // set the "pid" context.put("param_pid", ActionURL.PARAM_PID); context.put("pid", getPid(req)); String collectionId = contentHostingService .getSiteCollection(ToolManager.getCurrentPlacement().getContext()); context.put(CONTEXT_SITE_COLLECTION_ID, collectionId); // indicate which WYSIWYG editor to use in legacy tools String editor = EditorConfiguration.getWysiwigEditor(); context.put("sakai_editor", editor); context.put("editorConfig", new EditorConfiguration()); UsageSession session = UsageSessionService.getSession(); if (session != null) { // SAK-23047 Set the proper country code in the chef_start generated markup String userId = session.getUserId(); ResourceLoader rl = new ResourceLoader(userId); Locale locale = rl.getLocale(); String languageCode = locale.getLanguage(); String countryCode = locale.getCountry(); if (countryCode != null && countryCode.length() > 0) { languageCode += "_" + countryCode; } context.put("language", languageCode); context.put("dir", rl.getOrientation(locale)); String browserId = session.getBrowserId(); if (UsageSession.WIN_IE.equals(browserId) || UsageSession.WIN_MZ.equals(browserId) || UsageSession.WIN_NN.equals(browserId) || UsageSession.MAC_MZ.equals(browserId) || UsageSession.MAC_NN.equals(browserId)) { context.put("wysiwyg", "true"); } } try { // dispatch panels (Note: panel must be in the URL, not the body - this is not from the parsed params) String panel = ((ParameterParser) req.getAttribute(ATTR_PARAMS)).getString(ActionURL.PARAM_PANEL); /* * TODO: float support from before... // special case for floating and the Main panel: if (LAYOUT_MAIN.equals(panel)) { if (handleFloat(portlet, context, rundata, state)) return; } */ if (panel == null || "".equals(panel) || "null".equals(panel)) { // default to main panel panel = LAYOUT_MAIN; } else { // sanitize value panel = panel.replaceAll("[\r\n]", ""); } context.put("panel", panel); // form a method name "build" + panel name (first letter caps) + "PanelContext" // buildPanelContext( VelocityPortlet, Context, ControllerState, RunData ) Class[] types = new Class[4]; types[0] = VelocityPortlet.class; types[1] = Context.class; types[2] = RunData.class; types[3] = SessionState.class; // let our extension classes override the pannel name for the method String methodName = panelMethodName(panel); Method method = getClass().getMethod(methodName, types); Object[] args = new Object[4]; args[0] = portlet; args[1] = context; args[2] = rundata; args[3] = getState(req); String template = (String) method.invoke(this, args); // if the method did something like a redirect, we don't want to try to put out any more if (!res.isCommitted()) { if (template == null) { // pick the template for the panel - the base + "-" + panel template = (String) getContext(rundata).get("template") + "-" + panel; } // the vm file needs a path and an extension template = "/vm/" + template + ".vm"; // setup for old style alert StringBuilder buf = new StringBuilder(); String msg = (String) getState(req).getAttribute(STATE_MESSAGE); if (msg != null) { buf.append(msg); getState(req).removeAttribute(STATE_MESSAGE); } Alert alert = getAlert(req); if (!alert.isEmpty()) { buf.append(alert.peekAlert()); setVmReference(ALERT_ATTR, alert, req); } if (buf.length() > 0) { setVmReference("alertMessage", buf.toString(), req); } // setup for old style validator setVmReference("validator", m_validator, req); // set standard no-cache headers setNoCacheHeaders(res); // add a standard header includeVm("chef_header.vm", req, res); includeVm(template, req, res); // add a standard footer includeVm("chef_footer.vm", req, res); } } catch (NoSuchMethodException e) { try { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "NoSuchMethodException for panel name"); } catch (IOException e1) { // ignore } } catch (IllegalAccessException e) { throw new ToolException(e); } catch (InvocationTargetException e) { throw new ToolException(e); } catch (ServletException e) { throw new ToolException(e); } }
From source file:com.haulmont.cuba.web.App.java
protected Locale resolveLocale(@Nullable Locale requestLocale) { Map<String, Locale> locales = globalConfig.getAvailableLocales(); if (globalConfig.getLocaleSelectVisible()) { String lastLocale = getCookieValue(COOKIE_LOCALE); if (lastLocale != null) { for (Locale locale : locales.values()) { if (locale.toLanguageTag().equals(lastLocale)) { return locale; }//from w w w. jav a 2 s. c om } } } if (requestLocale != null) { Locale requestTrimmedLocale = messageTools.trimLocale(requestLocale); if (locales.containsValue(requestTrimmedLocale)) { return requestTrimmedLocale; } // if not found and application locale contains country, try to match by language only if (!StringUtils.isEmpty(requestLocale.getCountry())) { Locale appLocale = Locale.forLanguageTag(requestLocale.getLanguage()); for (Locale locale : locales.values()) { if (Locale.forLanguageTag(locale.getLanguage()).equals(appLocale)) { return locale; } } } } // return default locale return messageTools.getDefaultLocale(); }
From source file:com.frameworkset.platform.cms.driver.i18n.CmsLocaleManager.java
/** * Tries to find the given requested locale (eventually simplified) in the collection of available locales, * if the requested locale is not found it will return the first match from the given list of default locales.<p> * /* ww w. j a v a 2s.c o m*/ * @param requestedLocale the requested locale, if this (or a simplified version of it) is available it will be returned * @param defaults a list of default locales to use in case the requested locale is not available * @param available the available locales to find a match in * * @return the best matching locale name or null if no name matches */ public Locale getBestMatchingLocale(Locale requestedLocale, List defaults, Collection available) { if ((available == null) || available.isEmpty()) { // no locales are available at all return null; } // the requested locale is the match we want to find most if (available.contains(requestedLocale)) { // check if the requested locale is directly available return requestedLocale; } if (requestedLocale.getVariant().length() > 0) { // locale has a variant like "en_EN_whatever", try only with language and country Locale check = new Locale(requestedLocale.getLanguage(), requestedLocale.getCountry(), ""); if (available.contains(check)) { return check; } } if (requestedLocale.getCountry().length() > 0) { // locale has a country like "en_EN", try only with language Locale check = new Locale(requestedLocale.getLanguage(), "", ""); if (available.contains(check)) { return check; } } // available locales do not match the requested locale if ((defaults == null) || defaults.isEmpty()) { // if we have no default locales we are out of luck return null; } // no match found for the requested locale, return the first match from the default locales return getFirstMatchingLocale(defaults, available); }
From source file:com.icesoft.faces.application.D2DViewHandler.java
public Locale calculateLocale(FacesContext context) { Application application = context.getApplication(); Iterator acceptedLocales = context.getExternalContext().getRequestLocales(); while (acceptedLocales.hasNext()) { Locale acceptedLocale = (Locale) acceptedLocales.next(); Iterator supportedLocales = application.getSupportedLocales(); while (supportedLocales.hasNext()) { Locale supportedLocale = (Locale) supportedLocales.next(); if (acceptedLocale.equals(supportedLocale)) { return supportedLocale; }//from w ww .j a v a2 s. co m } supportedLocales = application.getSupportedLocales(); while (supportedLocales.hasNext()) { Locale supportedLocale = (Locale) supportedLocales.next(); if (acceptedLocale.getLanguage().equals(supportedLocale.getLanguage()) && supportedLocale.getCountry().length() == 0) { return supportedLocale; } } } // no match is found. Locale defaultLocale = application.getDefaultLocale(); return defaultLocale == null ? Locale.getDefault() : defaultLocale; }
From source file:org.deviceconnect.android.deviceplugin.irkit.IRKitManager.java
/** * regdomain??./* w w w.ja va 2 s . c o m*/ * * @return regdomain */ private String getRegDomain() { String regdomain = null; if (mCountryCode == null) { Locale locale = Locale.getDefault(); mCountryCode = locale.getCountry(); } if ("JP".equals(mCountryCode)) { regdomain = "2"; } else { for (String code : NOT_JP_COUNTRIES) { if (code.equals(mCountryCode)) { regdomain = "0"; break; } } if (regdomain == null) { regdomain = "1"; } } return regdomain; }