List of usage examples for java.util Locale getCountry
public String getCountry()
From source file:com.globalsight.machineTranslation.AbstractTranslator.java
private String[] trSafaba(Locale sourceLocale, Locale targetLocale, String[] segments) throws MachineTranslationException { boolean isXlf = MTHelper.isXlf(parameterMap); boolean needSpecialProcessingXlfSegs = MTHelper.needSpecialProcessingXlfSegs(parameterMap); int batchSize = determineBatchSize(); List<String> translatedList = new ArrayList<String>(); List<String> unTranslatedList = Arrays.asList(segments); boolean hasMore = true; while (hasMore) { List<String> subList = null; if (unTranslatedList.size() <= batchSize) { subList = unTranslatedList;/*from w ww.j a v a2s .c om*/ hasMore = false; } else { subList = unTranslatedList.subList(0, batchSize); unTranslatedList = unTranslatedList.subList(batchSize, unTranslatedList.size()); } Object[] segmentObjArray = subList.toArray(); String[] segmentsArray = new String[segmentObjArray.length]; for (int i = 0; i < segmentObjArray.length; i++) { segmentsArray[i] = (String) segmentObjArray[i]; } String[] subResults = null; if (SafabaProxy.DIRECT_TRANSLATE) { HashMap<Integer, List<String>> idListMap = new HashMap<Integer, List<String>>(); HashMap<Integer, List<String>> xListMap = new HashMap<Integer, List<String>>(); GxmlElement ge = null; List<String> heads = new ArrayList<String>(); String[] segmentsArray2 = new String[segmentsArray.length]; for (int i = 0; i < segmentsArray.length; i++) { int index = segmentsArray[i].indexOf(">"); String head = segmentsArray[i].substring(0, index + 1); heads.add(head); List<String> idList = null; List<String> xList = null; if (needSpecialProcessingXlfSegs) { ge = SegmentUtil2.getGxmlElement(segmentsArray[i]); if (ge != null) { idList = SegmentUtil2.getAttValuesByName(ge, "id"); idListMap.put(i, idList); xList = SegmentUtil2.getAttValuesByName(ge, "x"); xListMap.put(i, xList); } String locale = sourceLocale.getLanguage() + "_" + sourceLocale.getCountry(); String segNoRoot = GxmlUtil.stripRootTag(segmentsArray[i]); segNoRoot = MTHelper.wrappText(segNoRoot, locale); segNoRoot = MTHelper.revertXlfSegment(segNoRoot, locale); segNoRoot = MTHelper.encodeLtGtInGxmlAttributeValue(segNoRoot); segmentsArray2[i] = segNoRoot; } else { segmentsArray2[i] = GxmlUtil.stripRootTag(segmentsArray[i]); } } subResults = doBatchTranslation(sourceLocale, targetLocale, segmentsArray2); if (subResults != null && subResults.length == segmentsArray2.length) { for (int i = 0; i < subResults.length; i++) { String transResult = subResults[i]; if (needSpecialProcessingXlfSegs && StringUtil.isNotEmpty(transResult)) { transResult = transResult.replace("_gt;_", ">"); // handle single '&' in MT translation transResult = MTHelper.encodeSeparatedAndChar(transResult); // Parse the translation back DiplomatAPI api = getDiplomatApi(); SegmentNode sn = SegmentUtil2.extractSegment(api, transResult, "xlf", sourceLocale); if (sn != null) { transResult = sn.getSegment(); // Handle entity transResult = MTHelper.resetIdAndXAttributesValues(transResult, idListMap.get(i), xListMap.get(i)); } else { transResult = ""; } } subResults[i] = heads.get(i) + transResult + "</segment>"; } } } else if (isXlf) { subResults = translateAndPutTagsInFront(sourceLocale, targetLocale, segmentsArray); } else { subResults = translateSegmentsWithTags(sourceLocale, targetLocale, segmentsArray); } if (subResults != null) { translatedList.addAll(Arrays.asList(subResults)); } } String[] results = new String[segments.length]; for (int i = 0; i < translatedList.size(); i++) { String translatedSeg = translatedList.get(i); // If Safaba fails to translate, it will return source. String srcSegment = GxmlUtil.stripRootTag(segments[i]).trim(); String trgSegment = GxmlUtil.stripRootTag(translatedSeg).trim(); if (srcSegment != null && srcSegment.equals(trgSegment)) { translatedSeg = ""; } results[i] = translatedSeg; } return results; }
From source file:com.liferay.portal.events.ServicePreActionExt.java
protected void servicePre(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); // Company/*w ww . ja va2 s. c om*/ Company company = PortalUtil.getCompany(request); long companyId = company.getCompanyId(); // CDN host String cdnHost = null; if (request.isSecure()) { cdnHost = PortalUtil.getCDNHostHttps(); } else { cdnHost = PortalUtil.getCDNHostHttp(); } cdnHost = ParamUtil.getString(request, "cdn_host", cdnHost); // Portal URL String portalURL = PortalUtil.getPortalURL(request); // Paths String contextPath = PortalUtil.getPathContext(); String friendlyURLPrivateGroupPath = PortalUtil.getPathFriendlyURLPrivateGroup(); String friendlyURLPrivateUserPath = PortalUtil.getPathFriendlyURLPrivateUser(); String friendlyURLPublicPath = PortalUtil.getPathFriendlyURLPublic(); String imagePath = cdnHost.concat(PortalUtil.getPathImage()); String mainPath = PortalUtil.getPathMain(); String i18nPath = (String) request.getAttribute(WebKeys.I18N_PATH); if (Validator.isNotNull(i18nPath)) { if (Validator.isNotNull(contextPath)) { String i18nContextPath = contextPath.concat(i18nPath); friendlyURLPrivateGroupPath = StringUtil.replaceFirst(friendlyURLPrivateGroupPath, contextPath, i18nContextPath); friendlyURLPrivateUserPath = StringUtil.replaceFirst(friendlyURLPrivateUserPath, contextPath, i18nContextPath); friendlyURLPublicPath = StringUtil.replaceFirst(friendlyURLPublicPath, contextPath, i18nContextPath); mainPath = StringUtil.replaceFirst(mainPath, contextPath, i18nContextPath); } else { friendlyURLPrivateGroupPath = i18nPath.concat(friendlyURLPrivateGroupPath); friendlyURLPrivateUserPath = i18nPath.concat(friendlyURLPrivateUserPath); friendlyURLPublicPath = i18nPath.concat(friendlyURLPublicPath); mainPath = i18nPath.concat(mainPath); } } // Company logo StringBundler sb = new StringBundler(5); sb.append(imagePath); sb.append("/company_logo?img_id="); sb.append(company.getLogoId()); sb.append("&t="); sb.append(ImageServletTokenUtil.getToken(company.getLogoId())); String companyLogo = sb.toString(); Image companyLogoImage = ImageLocalServiceUtil.getCompanyLogo(company.getLogoId()); int companyLogoHeight = companyLogoImage.getHeight(); int companyLogoWidth = companyLogoImage.getWidth(); String realCompanyLogo = companyLogo; int realCompanyLogoHeight = companyLogoHeight; int realCompanyLogoWidth = companyLogoWidth; // User User user = null; try { user = PortalUtil.getUser(request); } catch (NoSuchUserException nsue) { if (_log.isWarnEnabled()) { _log.warn(nsue.getMessage()); } long userId = PortalUtil.getUserId(request); if (userId > 0) { session.invalidate(); } return; } boolean signedIn = false; if (user == null) { user = company.getDefaultUser(); } else if (!user.isDefaultUser()) { signedIn = true; } User realUser = user; Long realUserId = (Long) session.getAttribute(WebKeys.USER_ID); if (realUserId != null) { if (user.getUserId() != realUserId.longValue()) { realUser = UserLocalServiceUtil.getUserById(realUserId.longValue()); } } String doAsUserId = ParamUtil.getString(request, "doAsUserId"); String doAsUserLanguageId = ParamUtil.getString(request, "doAsUserLanguageId"); long doAsGroupId = ParamUtil.getLong(request, "doAsGroupId"); long refererPlid = ParamUtil.getLong(request, "refererPlid"); // Permission checker PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user, true); PermissionThreadLocal.setPermissionChecker(permissionChecker); // Locale Locale locale = (Locale) session.getAttribute(Globals.LOCALE_KEY); if (Validator.isNotNull(doAsUserLanguageId)) { locale = LocaleUtil.fromLanguageId(doAsUserLanguageId); } String i18nLanguageId = (String) request.getAttribute(WebKeys.I18N_LANGUAGE_ID); if (Validator.isNotNull(i18nLanguageId)) { locale = LocaleUtil.fromLanguageId(i18nLanguageId); } else if (locale == null) { if (signedIn) { locale = user.getLocale(); } else { // User previously set their preferred language String languageId = CookieKeys.getCookie(request, CookieKeys.GUEST_LANGUAGE_ID); if (Validator.isNotNull(languageId)) { locale = LocaleUtil.fromLanguageId(languageId); } // Get locale from the request if ((locale == null) && PropsValues.LOCALE_DEFAULT_REQUEST) { locale = request.getLocale(); } // Get locale from the default user if (locale == null) { locale = user.getLocale(); } if (Validator.isNull(locale.getCountry())) { // Locales must contain a country code locale = LanguageUtil.getLocale(locale.getLanguage()); } if (!LanguageUtil.isAvailableLocale(locale)) { locale = user.getLocale(); } } session.setAttribute(Globals.LOCALE_KEY, locale); LanguageUtil.updateCookie(request, response, locale); } // Cookie support try { // LEP-4069 CookieKeys.validateSupportCookie(request); } catch (Exception e) { CookieKeys.addSupportCookie(request, response); } // Time zone TimeZone timeZone = user.getTimeZone(); if (timeZone == null) { timeZone = company.getTimeZone(); } // Layouts if (signedIn) { updateUserLayouts(user); } Layout layout = null; List<Layout> layouts = null; long plid = ParamUtil.getLong(request, "p_l_id"); if (plid > 0) { layout = LayoutLocalServiceUtil.getLayout(plid); } else { long groupId = ParamUtil.getLong(request, "groupId"); boolean privateLayout = ParamUtil.getBoolean(request, "privateLayout"); long layoutId = ParamUtil.getLong(request, "layoutId"); if ((groupId > 0) && layoutId > 0) { layout = LayoutLocalServiceUtil.getLayout(groupId, privateLayout, layoutId); } } if (layout != null) { try { Group group = layout.getGroup(); if (!signedIn && PropsValues.AUTH_FORWARD_BY_REDIRECT) { request.setAttribute(WebKeys.REQUESTED_LAYOUT, layout); } boolean isViewableCommunity = isViewableGroup(user, layout.getGroupId(), layout.isPrivateLayout(), layout.getLayoutId(), permissionChecker); if (!isViewableCommunity && group.isStagingGroup()) { layout = null; } else if (!isViewableCommunity) { sb = new StringBundler(6); sb.append("User "); sb.append(user.getUserId()); sb.append(" is not allowed to access the "); sb.append(layout.isPrivateLayout() ? "private" : "public"); sb.append(" pages of group "); sb.append(layout.getGroupId()); if (_log.isWarnEnabled()) { _log.warn(sb.toString()); } throw new PrincipalException(sb.toString()); } else if (isViewableCommunity && !LayoutPermissionUtil.contains(permissionChecker, layout, ActionKeys.VIEW)) { layout = null; } else if (group.isLayoutPrototype()) { layouts = new ArrayList<Layout>(); } else { layouts = LayoutLocalServiceUtil.getLayouts(layout.getGroupId(), layout.isPrivateLayout(), LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); if (!group.isControlPanel()) { doAsGroupId = 0; } } } catch (NoSuchLayoutException nsle) { } } if (layout == null) { Object[] defaultLayout = getDefaultLayout(request, user, signedIn); layout = (Layout) defaultLayout[0]; layouts = (List<Layout>) defaultLayout[1]; request.setAttribute(WebKeys.LAYOUT_DEFAULT, Boolean.TRUE); } Object[] viewableLayouts = getViewableLayouts(request, user, permissionChecker, layout, layouts); String layoutSetLogo = null; layout = (Layout) viewableLayouts[0]; layouts = (List<Layout>) viewableLayouts[1]; Group group = null; if (layout != null) { group = layout.getGroup(); if (!group.isControlPanel()) { rememberVisitedGroupIds(request, group.getGroupId()); } } LayoutTypePortlet layoutTypePortlet = null; layouts = mergeAdditionalLayouts(request, user, permissionChecker, layout, layouts); if (layout != null) { if (company.isCommunityLogo()) { long logoId = 0; LayoutSet layoutSet = layout.getLayoutSet(); if (layoutSet.isLogo()) { logoId = layoutSet.getLogoId(); } else { LayoutSet siblingLayoutSet = LayoutSetLocalServiceUtil.getLayoutSet(layout.getGroupId(), !layout.isPrivateLayout()); if (siblingLayoutSet.isLogo()) { logoId = siblingLayoutSet.getLogoId(); } } if (logoId > 0) { sb = new StringBundler(5); sb.append(imagePath); sb.append("/layout_set_logo?img_id="); sb.append(logoId); sb.append("&t="); sb.append(ImageServletTokenUtil.getToken(logoId)); layoutSetLogo = sb.toString(); Image layoutSetLogoImage = ImageLocalServiceUtil.getCompanyLogo(logoId); companyLogo = layoutSetLogo; companyLogoHeight = layoutSetLogoImage.getHeight(); companyLogoWidth = layoutSetLogoImage.getWidth(); } } plid = layout.getPlid(); // Updates to shared layouts are not reflected until the next time // the user logs in because group layouts are cached in the session layout = (Layout) ((LayoutImpl) layout).clone(); layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType(); LayoutClone layoutClone = LayoutCloneFactory.getInstance(); if (layoutClone != null) { String typeSettings = layoutClone.get(request, plid); if (typeSettings != null) { UnicodeProperties props = new UnicodeProperties(true); props.load(typeSettings); String stateMax = props.getProperty(LayoutTypePortletConstants.STATE_MAX); String stateMin = props.getProperty(LayoutTypePortletConstants.STATE_MIN); String modeAbout = props.getProperty(LayoutTypePortletConstants.MODE_ABOUT); String modeConfig = props.getProperty(LayoutTypePortletConstants.MODE_CONFIG); String modeEdit = props.getProperty(LayoutTypePortletConstants.MODE_EDIT); String modeEditDefaults = props.getProperty(LayoutTypePortletConstants.MODE_EDIT_DEFAULTS); String modeEditGuest = props.getProperty(LayoutTypePortletConstants.MODE_EDIT_GUEST); String modeHelp = props.getProperty(LayoutTypePortletConstants.MODE_HELP); String modePreview = props.getProperty(LayoutTypePortletConstants.MODE_PREVIEW); String modePrint = props.getProperty(LayoutTypePortletConstants.MODE_PRINT); layoutTypePortlet.setStateMax(stateMax); layoutTypePortlet.setStateMin(stateMin); layoutTypePortlet.setModeAbout(modeAbout); layoutTypePortlet.setModeConfig(modeConfig); layoutTypePortlet.setModeEdit(modeEdit); layoutTypePortlet.setModeEditDefaults(modeEditDefaults); layoutTypePortlet.setModeEditGuest(modeEditGuest); layoutTypePortlet.setModeHelp(modeHelp); layoutTypePortlet.setModePreview(modePreview); layoutTypePortlet.setModePrint(modePrint); } } request.setAttribute(WebKeys.LAYOUT, layout); request.setAttribute(WebKeys.LAYOUTS, layouts); if (layout.isPrivateLayout()) { permissionChecker.setCheckGuest(false); } } // Scope long scopeGroupId = PortalUtil.getScopeGroupId(request); long parentGroupId = PortalUtil.getParentGroupId(scopeGroupId); // Device Device device = DevicesUtil.getDeviceFromRequest(request); _log.debug(" Device is: " + device); // Theme and color scheme Theme theme = null; ColorScheme colorScheme = null; boolean wapTheme = BrowserSnifferUtil.isWap(request); if ((layout != null) && group.isControlPanel()) { String themeId = PrefsPropsUtil.getString(companyId, PropsKeys.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID); String colorSchemeId = ColorSchemeImpl.getDefaultRegularColorSchemeId(); theme = ThemeLocalServiceUtil.getTheme(companyId, themeId, wapTheme); colorScheme = ThemeLocalServiceUtil.getColorScheme(companyId, theme.getThemeId(), colorSchemeId, wapTheme); if (!wapTheme && theme.isWapTheme()) { theme = ThemeLocalServiceUtil.getTheme(companyId, PropsValues.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID, false); colorScheme = ThemeLocalServiceUtil.getColorScheme(companyId, theme.getThemeId(), colorSchemeId, false); } } else { DeviceAction deviceAction = DeviceRulesUtil.getAction(device, companyId, group.getGroupId(), layout.getPlid()); if (deviceAction != null && !(deviceAction instanceof NoAction)) { if (deviceAction instanceof ChangeThemeAction) { ChangeThemeAction changeThemeAction = (ChangeThemeAction) deviceAction; ThemeAndColorScheme themeAndColorScheme = changeThemeAction.getThemeAndColorScheme(); if (themeAndColorScheme != null && themeAndColorScheme.getThemeId() != null) { theme = themeAndColorScheme.getTheme(companyId); _log.debug("Changing theme to " + theme.getThemeId()); if (themeAndColorScheme.getColorSchemeId() != null) { colorScheme = themeAndColorScheme.getColorScheme(companyId); _log.debug("Changing color scheme to " + colorScheme.getColorSchemeId()); } } } if (deviceAction instanceof RedirectAction) { RedirectAction redirectAction = (RedirectAction) deviceAction; String url = redirectAction.getUrl(); if (url != null && !url.trim().isEmpty()) { _log.debug("Redirecting to " + url); response.sendRedirect(url); return; } } } else if (layout != null) { if (wapTheme) { theme = layout.getWapTheme(); colorScheme = layout.getWapColorScheme(); } else { theme = layout.getTheme(); colorScheme = layout.getColorScheme(); } } else { String themeId = null; String colorSchemeId = null; if (wapTheme) { themeId = ThemeImpl.getDefaultWapThemeId(companyId); colorSchemeId = ColorSchemeImpl.getDefaultWapColorSchemeId(); } else { themeId = ThemeImpl.getDefaultRegularThemeId(companyId); colorSchemeId = ColorSchemeImpl.getDefaultRegularColorSchemeId(); } theme = ThemeLocalServiceUtil.getTheme(companyId, themeId, wapTheme); colorScheme = ThemeLocalServiceUtil.getColorScheme(companyId, theme.getThemeId(), colorSchemeId, wapTheme); } } request.setAttribute(WebKeys.THEME, theme); request.setAttribute(WebKeys.COLOR_SCHEME, colorScheme); boolean themeCssFastLoad = SessionParamUtil.getBoolean(request, "css_fast_load", PropsValues.THEME_CSS_FAST_LOAD); boolean themeImagesFastLoad = SessionParamUtil.getBoolean(request, "images_fast_load", PropsValues.THEME_IMAGES_FAST_LOAD); boolean themeJsBarebone = PropsValues.JAVASCRIPT_BAREBONE_ENABLED; if (themeJsBarebone) { if (signedIn) { themeJsBarebone = false; } } boolean themeJsFastLoad = SessionParamUtil.getBoolean(request, "js_fast_load", PropsValues.JAVASCRIPT_FAST_LOAD); String lifecycle = ParamUtil.getString(request, "p_p_lifecycle", "0"); boolean isolated = ParamUtil.getBoolean(request, "p_p_isolated"); String facebookCanvasPageURL = (String) request.getAttribute(WebKeys.FACEBOOK_CANVAS_PAGE_URL); boolean widget = false; Boolean widgetObj = (Boolean) request.getAttribute(WebKeys.WIDGET); if (widgetObj != null) { widget = widgetObj.booleanValue(); } // Theme display ThemeDisplay themeDisplay = ThemeDisplayFactory.create(); // Set the CDN host, portal URL, and Facebook application ID first // because other methods (setLookAndFeel) depend on them being set themeDisplay.setCDNHost(cdnHost); themeDisplay.setPortalURL(portalURL); themeDisplay.setFacebookCanvasPageURL(facebookCanvasPageURL); themeDisplay.setWidget(widget); themeDisplay.setCompany(company); themeDisplay.setCompanyLogo(companyLogo); themeDisplay.setCompanyLogoHeight(companyLogoHeight); themeDisplay.setCompanyLogoWidth(companyLogoWidth); themeDisplay.setRealCompanyLogo(realCompanyLogo); themeDisplay.setRealCompanyLogoHeight(realCompanyLogoHeight); themeDisplay.setRealCompanyLogoWidth(realCompanyLogoWidth); themeDisplay.setUser(user); themeDisplay.setRealUser(realUser); themeDisplay.setDoAsUserId(doAsUserId); themeDisplay.setDoAsUserLanguageId(doAsUserLanguageId); themeDisplay.setDoAsGroupId(doAsGroupId); themeDisplay.setRefererPlid(refererPlid); themeDisplay.setLayoutSetLogo(layoutSetLogo); themeDisplay.setLayout(layout); themeDisplay.setLayouts(layouts); themeDisplay.setPlid(plid); themeDisplay.setLayoutTypePortlet(layoutTypePortlet); themeDisplay.setScopeGroupId(scopeGroupId); themeDisplay.setParentGroupId(parentGroupId); themeDisplay.setSignedIn(signedIn); themeDisplay.setPermissionChecker(permissionChecker); themeDisplay.setLocale(locale); themeDisplay.setLanguageId(LocaleUtil.toLanguageId(locale)); themeDisplay.setI18nLanguageId(i18nLanguageId); themeDisplay.setI18nPath(i18nPath); themeDisplay.setTimeZone(timeZone); themeDisplay.setLookAndFeel(contextPath, theme, colorScheme); themeDisplay.setThemeCssFastLoad(themeCssFastLoad); themeDisplay.setThemeImagesFastLoad(themeImagesFastLoad); themeDisplay.setThemeJsBarebone(themeJsBarebone); themeDisplay.setThemeJsFastLoad(themeJsFastLoad); themeDisplay.setServerName(request.getServerName()); themeDisplay.setServerPort(request.getServerPort()); themeDisplay.setSecure(request.isSecure()); themeDisplay.setLifecycle(lifecycle); themeDisplay.setLifecycleAction(lifecycle.equals("1")); themeDisplay.setLifecycleRender(lifecycle.equals("0")); themeDisplay.setLifecycleResource(lifecycle.equals("2")); themeDisplay.setStateExclusive(LiferayWindowState.isExclusive(request)); themeDisplay.setStateMaximized(LiferayWindowState.isMaximized(request)); themeDisplay.setStatePopUp(LiferayWindowState.isPopUp(request)); themeDisplay.setIsolated(isolated); themeDisplay.setPathApplet(contextPath.concat("/applets")); themeDisplay.setPathCms(contextPath.concat("/cms")); themeDisplay.setPathContext(contextPath); themeDisplay.setPathFlash(contextPath.concat("/flash")); themeDisplay.setPathFriendlyURLPrivateGroup(friendlyURLPrivateGroupPath); themeDisplay.setPathFriendlyURLPrivateUser(friendlyURLPrivateUserPath); themeDisplay.setPathFriendlyURLPublic(friendlyURLPublicPath); themeDisplay.setPathImage(imagePath); themeDisplay.setPathJavaScript(cdnHost.concat(contextPath).concat("/html/js")); themeDisplay.setPathMain(mainPath); themeDisplay.setPathSound(contextPath.concat("/html/sound")); // URLs themeDisplay.setShowAddContentIcon(false); themeDisplay.setShowControlPanelIcon(signedIn); themeDisplay.setShowHomeIcon(true); themeDisplay.setShowMyAccountIcon(signedIn); themeDisplay.setShowPageSettingsIcon(false); themeDisplay.setShowPortalIcon(true); themeDisplay.setShowSignInIcon(!signedIn); themeDisplay.setShowSignOutIcon(signedIn); themeDisplay.setShowStagingIcon(false); String urlControlPanel = friendlyURLPrivateGroupPath.concat(GroupConstants.CONTROL_PANEL_FRIENDLY_URL); if (Validator.isNotNull(doAsUserId)) { urlControlPanel = HttpUtil.addParameter(urlControlPanel, "doAsUserId", doAsUserId); } if (scopeGroupId > 0) { urlControlPanel = HttpUtil.addParameter(urlControlPanel, "doAsGroupId", scopeGroupId); } if (refererPlid > 0) { urlControlPanel = HttpUtil.addParameter(urlControlPanel, "refererPlid", refererPlid); } else if (plid > 0) { urlControlPanel = HttpUtil.addParameter(urlControlPanel, "refererPlid", plid); } themeDisplay.setURLControlPanel(urlControlPanel); PortletURL createAccountURL = new PortletURLImpl(request, PortletKeys.LOGIN, plid, PortletRequest.ACTION_PHASE); createAccountURL.setWindowState(WindowState.MAXIMIZED); createAccountURL.setPortletMode(PortletMode.VIEW); createAccountURL.setParameter("saveLastPath", "0"); createAccountURL.setParameter("struts_action", "/login/create_account"); themeDisplay.setURLCreateAccount(createAccountURL); String currentURL = PortalUtil.getCurrentURL(request); themeDisplay.setURLCurrent(currentURL); String urlHome = PortalUtil.getHomeURL(request); themeDisplay.setURLHome(urlHome); if (layout != null) { if (layout.isTypePortlet()) { boolean freeformLayout = layoutTypePortlet.getLayoutTemplateId().equals("freeform"); themeDisplay.setFreeformLayout(freeformLayout); boolean hasUpdateLayoutPermission = LayoutPermissionUtil.contains(permissionChecker, layout, ActionKeys.UPDATE); if (hasUpdateLayoutPermission) { themeDisplay.setShowAddContentIconPermission(true); if (!LiferayWindowState.isMaximized(request)) { themeDisplay.setShowAddContentIcon(true); } themeDisplay.setShowLayoutTemplatesIcon(true); themeDisplay.setURLAddContent("Liferay.LayoutConfiguration.toggle('" .concat(PortletKeys.LAYOUT_CONFIGURATION).concat("');")); themeDisplay.setURLLayoutTemplates("Liferay.LayoutConfiguration.showTemplates();"); } } boolean hasManageLayoutsPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId, ActionKeys.MANAGE_LAYOUTS); if (group.isUser()) { if ((layout.isPrivateLayout() && !PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_MODIFIABLE) || (layout.isPublicLayout() && !PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_MODIFIABLE)) { hasManageLayoutsPermission = false; } } if (hasManageLayoutsPermission) { themeDisplay.setShowPageSettingsIcon(true); PortletURL pageSettingsURL = new PortletURLImpl(request, PortletKeys.LAYOUT_MANAGEMENT, plid, PortletRequest.RENDER_PHASE); pageSettingsURL.setWindowState(WindowState.MAXIMIZED); pageSettingsURL.setPortletMode(PortletMode.VIEW); pageSettingsURL.setParameter("struts_action", "/layout_management/edit_pages"); if (layout.isPrivateLayout()) { pageSettingsURL.setParameter("tabs1", "private-pages"); } else { pageSettingsURL.setParameter("tabs1", "public-pages"); } pageSettingsURL.setParameter("redirect", currentURL); pageSettingsURL.setParameter("groupId", String.valueOf(scopeGroupId)); pageSettingsURL.setParameter("selPlid", String.valueOf(plid)); themeDisplay.setURLPageSettings(pageSettingsURL); } if (group.hasStagingGroup() && !group.isStagingGroup()) { themeDisplay.setShowAddContentIcon(false); themeDisplay.setShowLayoutTemplatesIcon(false); themeDisplay.setShowPageSettingsIcon(false); themeDisplay.setURLPublishToLive(null); } if (group.isControlPanel()) { themeDisplay.setShowPageSettingsIcon(false); themeDisplay.setURLPublishToLive(null); } // LEP-4987 if (group.isStaged() || group.isStagingGroup()) { boolean hasApproveProposalPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId, ActionKeys.APPROVE_PROPOSAL); boolean hasPublishStagingPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId, ActionKeys.PUBLISH_STAGING); if (hasApproveProposalPermission || hasManageLayoutsPermission || hasPublishStagingPermission) { themeDisplay.setShowStagingIcon(true); } if (hasPublishStagingPermission) { PortletURL publishToLiveURL = new PortletURLImpl(request, PortletKeys.LAYOUT_MANAGEMENT, plid, PortletRequest.RENDER_PHASE); publishToLiveURL.setWindowState(LiferayWindowState.EXCLUSIVE); publishToLiveURL.setPortletMode(PortletMode.VIEW); publishToLiveURL.setParameter("struts_action", "/layout_management/export_pages"); if (layout.isPrivateLayout()) { publishToLiveURL.setParameter("tabs1", "private-pages"); } else { publishToLiveURL.setParameter("tabs1", "public-pages"); } publishToLiveURL.setParameter("pagesRedirect", currentURL); publishToLiveURL.setParameter("groupId", String.valueOf(scopeGroupId)); publishToLiveURL.setParameter("selPlid", String.valueOf(plid)); themeDisplay.setURLPublishToLive(publishToLiveURL); } } String myAccountNamespace = PortalUtil.getPortletNamespace(PortletKeys.MY_ACCOUNT); String myAccountRedirect = ParamUtil.getString(request, myAccountNamespace.concat("backURL"), currentURL); Group controlPanelGroup = GroupLocalServiceUtil.getGroup(companyId, GroupConstants.CONTROL_PANEL); long controlPanelPlid = LayoutLocalServiceUtil.getDefaultPlid(controlPanelGroup.getGroupId(), true); PortletURLImpl myAccountURL = new PortletURLImpl(request, PortletKeys.MY_ACCOUNT, controlPanelPlid, PortletRequest.RENDER_PHASE); myAccountURL.setWindowState(WindowState.MAXIMIZED); myAccountURL.setPortletMode(PortletMode.VIEW); myAccountURL.setRefererPlid(plid); myAccountURL.setParameter("struts_action", "/my_account/edit_user"); myAccountURL.setParameter("backURL", myAccountRedirect); themeDisplay.setURLMyAccount(myAccountURL); } if ((!user.isActive()) || (PrefsPropsUtil.getBoolean(companyId, PropsKeys.TERMS_OF_USE_REQUIRED) && !user.isAgreedToTermsOfUse())) { themeDisplay.setShowAddContentIcon(false); themeDisplay.setShowMyAccountIcon(false); themeDisplay.setShowPageSettingsIcon(false); } if (group.isLayoutPrototype()) { themeDisplay.setShowControlPanelIcon(false); themeDisplay.setShowHomeIcon(false); themeDisplay.setShowMyAccountIcon(false); themeDisplay.setShowPageSettingsIcon(true); themeDisplay.setShowPortalIcon(false); themeDisplay.setShowSignInIcon(false); themeDisplay.setShowSignOutIcon(false); themeDisplay.setShowStagingIcon(false); } themeDisplay.setURLPortal(portalURL.concat(contextPath)); String urlSignIn = mainPath.concat("/portal/login"); if (layout != null) { urlSignIn = HttpUtil.addParameter(urlSignIn, "p_l_id", layout.getPlid()); } themeDisplay.setURLSignIn(urlSignIn); themeDisplay.setURLSignOut(mainPath.concat("/portal/logout")); PortletURL updateManagerURL = new PortletURLImpl(request, PortletKeys.UPDATE_MANAGER, plid, PortletRequest.RENDER_PHASE); updateManagerURL.setWindowState(WindowState.MAXIMIZED); updateManagerURL.setPortletMode(PortletMode.VIEW); updateManagerURL.setParameter("struts_action", "/update_manager/view"); themeDisplay.setURLUpdateManager(updateManagerURL); request.setAttribute(WebKeys.THEME_DISPLAY, themeDisplay); // Parallel render boolean parallelRenderEnable = true; if (layout != null) { List<String> portletIds = layoutTypePortlet.getPortletIds(); if (portletIds.size() == 1) { String portletId = portletIds.get(0); Portlet portlet = PortletLocalServiceUtil.getPortletById(portletId); if ((portlet != null) && !portlet.isAjaxable()) { parallelRenderEnable = false; } } } Boolean parallelRenderEnableObj = Boolean .valueOf(ParamUtil.getBoolean(request, "p_p_parallel", parallelRenderEnable)); request.setAttribute(WebKeys.PORTLET_PARALLEL_RENDER, parallelRenderEnableObj); }
From source file:com.android.server.MountService.java
private void copyLocaleFromMountService() { String systemLocale;//from ww w . jav a 2s . co m try { systemLocale = getField(StorageManager.SYSTEM_LOCALE_KEY); } catch (RemoteException e) { return; } if (TextUtils.isEmpty(systemLocale)) { return; } Slog.d(TAG, "Got locale " + systemLocale + " from mount service"); Locale locale = Locale.forLanguageTag(systemLocale); Configuration config = new Configuration(); config.setLocale(locale); try { ActivityManagerNative.getDefault().updateConfiguration(config); } catch (RemoteException e) { Slog.e(TAG, "Error setting system locale from mount service", e); } // Temporary workaround for http://b/17945169. Slog.d(TAG, "Setting system properties to " + systemLocale + " from mount service"); SystemProperties.set("persist.sys.language", locale.getLanguage()); SystemProperties.set("persist.sys.country", locale.getCountry()); }
From source file:net.sf.dvstar.transmission.TransmissionView.java
private void initLocale() { List<Locale> listLocales = Tools.getListOfAvailLanguages(); for (int i = 0; i < listLocales.size(); i++) { Locale locale = listLocales.get(i); String country = locale.getCountry().length() > 0 ? locale.getCountry() : "uk"; String flag = "/net/sf/dvstar/transmission/resources/images/flags/flags_" + country.toLowerCase() + ".png"; URL urlFlag = getClass().getResource(flag); ImageIcon iconFlag = new ImageIcon(urlFlag); JMenuItem miLocale;//from w w w . j av a2 s . co m if (iconFlag != null) { miLocale = new JMenuItem(locale.getDisplayLanguage(Locale.ENGLISH), iconFlag); } else { miLocale = new JMenuItem(locale.getDisplayLanguage(Locale.ENGLISH)); } miLocale.addActionListener(new LocaleActionListener(locale)); mnConfigLocale.add(miLocale); } }
From source file:com.yaodu.framework.controller.product.ProductSearchController.java
/** * /*from w w w . j a v a 2 s . c o m*/ * @description ?? * @author Ali Cao * @date 201537 * @param request * @param searchTxt * @param model * @return */ @RequestMapping(value = "/searchProductBaseInfo") public ModelAndView searchProductBaseInfo(@RequestParam(required = false, defaultValue = "1") int pageNo, @RequestParam(required = false) Integer pageSize, @RequestParam(required = false, defaultValue = "2") int showModel, HttpServletRequest request, String searchTxt, ModelAndView model) { long l1 = new Date().getTime(); if (log.isDebugEnabled()) { log.debug("entering searchProductBaseInfo(String,Model) method"); } CustomerInfo temCustomerInfo = (CustomerInfo) request.getSession().getAttribute("customerInfo"); Integer memberId = null; if (temCustomerInfo != null) { memberId = temCustomerInfo.getId(); } Map<String, Set<String>> drugTypeMap = null; List<Map.Entry<String, String>> therapyDomainMap = null; // ? List<ProductBascInfo> newProList = null; HttpSession session = request.getSession(); Pager pager = (Pager) session.getAttribute("page"); //add 2015-05-04 yannis ? bug 898 ????2040????????20 if (pageSize == null) { if (pager == null) { pageSize = 20; } else { pageSize = pager.getPageSize(); } } @SuppressWarnings("unchecked") List<ProductBascInfo> productsList = (List<ProductBascInfo>) session.getAttribute("productsList"); Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request); // ?json?????? if (null != searchTxt && !"".equals(searchTxt)) { SearchCondition searchCondition = SearchUtil.getSearchCondition(searchTxt); if (searchCondition != null) { session.setAttribute("sortByTime", searchCondition.getSortByTime()); session.setAttribute("sortByCharactor", searchCondition.getSortByCharactor()); if ((searchCondition.getSortByTime() == null || "".equals(searchCondition.getSortByTime())) && (null == searchCondition.getSortByCharactor() || "".equals(searchCondition.getSortByCharactor()))) { searchCondition.setSortByTime("d"); session.setAttribute("sortByTime", searchCondition.getSortByTime()); } List<NIds> list = null; // ?? ? if (searchCondition.getSearchTxt() != null && !"".equals(searchCondition.getSearchTxt())) { list = getIdsByKeyWord(searchCondition.getSearchTxt()); // ?? ?HotTpic } else if (searchCondition.getHotTopicId() != null && !"".equals(searchCondition.getHotTopicId())) { String name = SearchUtil.getHotTopicNameById(productSearchService, Integer.valueOf(searchCondition.getHotTopicId()).intValue()); Map<String, String> hotTopic = new HashMap<String, String>(); hotTopic.put(searchCondition.getHotTopicId(), name); model.addObject("hotTopic", hotTopic); model.addObject("hotTopicName", name); list = getIdsByHotpic(searchCondition.getHotTopicId()); // ?? } else if ((searchCondition.getDrugClassificationOne() != null && !"".equals(searchCondition.getDrugClassificationOne())) || (((searchCondition.getDrugClassificationOne() != null && !"".equals(searchCondition.getDrugClassificationOne())) && (searchCondition.getDrugClassificationTwo() != null && !"".equals(searchCondition.getDrugClassificationTwo()))))) { String classificationOneId = searchCondition.getDrugClassificationOne(); if (!classificationOneId.isEmpty()) { Map<String, String> drugClassificationOne = new HashMap<String, String>(); String name = ""; Menu menu = SearchUtil.getClassificationNameById(productSearchService, classificationOneId); if (null != menu) { if (!locale.getCountry().equals("CN")) { name = menu.getLabelEn(); } else { name = menu.getName(); } } drugClassificationOne.put(classificationOneId, name); model.addObject("drugClassificationOne", drugClassificationOne); model.addObject("drugClassificationOneName", name); } String classificationTwoId = searchCondition.getDrugClassificationTwo(); if (!classificationTwoId.isEmpty()) { Map<String, String> drugClassificationTwo = new HashMap<String, String>(); String name = ""; Menu menu = SearchUtil.getClassificationNameById(productSearchService, classificationTwoId); if (null != menu) { if (!locale.getCountry().equals("CN")) { name = menu.getLabelEn(); } else { name = menu.getName(); } } drugClassificationTwo.put(classificationTwoId, name); model.addObject("drugClassificationTwo", drugClassificationTwo); model.addObject("drugClassificationTwoName", name); } list = getIdsByClassification(searchCondition.getDrugClassificationOne(), searchCondition.getDrugClassificationTwo()); // ?? ??? } else if (searchCondition.getTargets() != null && searchCondition.getTargets().size() > 0) { list = productSolrjSearchService.getIdsByTarget(searchTxt); } List<String> nIds = changeList(list); searchCondition.setnIds(nIds); // customer first research if (null == productsList || pageNo == 1) { productsList = null; pager = null; pager = new Pager(); pager.setPageSize(pageSize); if (searchCondition.getSearchTxt() != null && !"".equals(searchCondition.getSearchTxt())) { if (nIds != null && nIds.size() > 0) { productsList = productSolrjSearchService.searchProductBaseInfo(searchCondition); } } else if (searchCondition.getHotTopicId() != null && !"".equals(searchCondition.getHotTopicId())) { if (nIds != null && nIds.size() > 0) { productsList = productSolrjSearchService.searchProductBaseInfo(searchCondition); } } else { productsList = productSolrjSearchService.searchProductBaseInfo(searchCondition); } session.setAttribute("productsList", productsList); session.setAttribute("page", pager); pager.setRecordCount(productsList == null ? 0 : productsList.size()); pager.setPageCount(pager.getPageCount()); } PageListUtils.fillPageInfo(pageNo, pager); newProList = PageListUtils.getNewProList(productsList, pager); newProList = PageListUtils.fillNewList(newProList, myFavoriteControllerService, memberId); drugTypeMap = getDrugType(productsList); therapyDomainMap = getTherapyDomain(targetStr, locale); } // ????? if (null != searchCondition.getTherapyDomain() && searchCondition.getTherapyDomain().size() > 0) { List<String> lst = searchCondition.getTherapyDomain(); List<Map<String, String>> lstTherapyDomain = null; if (lst != null && lst.size() > 0) { lstTherapyDomain = new ArrayList<Map<String, String>>(); for (int i = 0; i < lst.size(); i++) { Map<String, String> therapyDomain = new HashMap<String, String>(); String cat_id = lst.get(i); String name = ""; Menu menu = SearchUtil.getClassificationNameById(productSearchService, cat_id); if (null != menu) { if (!locale.getCountry().equals("CN")) { name = menu.getLabelEn(); } else { name = menu.getName(); } } therapyDomain.put(cat_id, name); lstTherapyDomain.add(therapyDomain); } } model.addObject("lstTherapyDomain", lstTherapyDomain); } model.addObject("searchTxt", searchCondition.getSearchTxt()); model.addObject("searchCondition", searchCondition); } else { // find all Object sortByTime = session.getAttribute("sortByTime"); Object sortByChar = session.getAttribute("sortByCharactor"); SearchCondition searchCondition = new SearchCondition(); if (null != sortByTime && !"".equals(sortByTime)) { searchCondition.setSortByTime(sortByTime.toString()); } else if (null != sortByChar && !"".equals(sortByChar)) { searchCondition.setSortByCharactor(sortByChar.toString()); } else { searchCondition.setSortByTime("d"); session.setAttribute("sortByTime", "d"); } if (null == productsList || pageNo == 1) { productsList = null; pager = null; pager = new Pager(); pager.setPageSize(pageSize); productsList = productSolrjSearchService.findAllProducts(searchCondition); session.setAttribute("productsList", productsList); session.setAttribute("page", pager); pager.setRecordCount(productsList.size()); pager.setPageCount(pager.getPageCount()); } PageListUtils.fillPageInfo(pageNo, pager); newProList = PageListUtils.getNewProList(productsList, pager); newProList = PageListUtils.fillNewList(newProList, myFavoriteControllerService, null); drugTypeMap = getDrugType(productsList); therapyDomainMap = getTherapyDomain(targetStr, locale); } List<ProductBascInfo> recentlyViewedList = new ProductUtils().getRecentlyViewedList(request, productSolrjSearchService); model.addObject("drugTypeMap", drugTypeMap); model.addObject("therapyDomain", therapyDomainMap); model.addObject("newProList", newProList); model.addObject("recentlyViewedList", recentlyViewedList); model.addObject("pager", pager); // hotTopic? add GaoFei 2015-03-09 List<HotTopic> hotTopicList = productBasicInfoService.getHotTopicList(); model.addObject("hotTopicList", hotTopicList); //?? model.addObject("showModel", showModel); long l2 = new Date().getTime(); log.info("search pros used times ----------->" + (l2 - l1) + " ms"); model.setViewName("product/searchResults"); return model; }
From source file:org.olat.core.util.i18n.I18nManager.java
private final String getLocalizedString(String bundleName, String key, Object[] args, Locale locale, boolean overlayEnabled, boolean fallBackToDefaultLocale, boolean fallBackToFallbackLocale, boolean resolveRecursively, boolean allowDecoration, int recursionLevel) { String msg = null;/*ww w.j a va 2 s . com*/ Properties properties = null; // a) If the overlay is enabled, lookup first in the overlay property // file if (overlayEnabled) { Locale overlayLocale = I18nModule.getOverlayLocales().get(locale); if (overlayLocale != null) { properties = getProperties(overlayLocale, bundleName, resolveRecursively, recursionLevel); if (properties != null) { msg = properties.getProperty(key); // if (log.isDebug() && msg == null) { // log.debug("Key::" + key + " not found in overlay::" + I18nModule.getOverlayName() + " for bundle::" + bundleName // + " and locale::" + locale.toString(), null); // } } } } // b) Otherwhise lookup in the regular bundle if (msg == null) { properties = getProperties(locale, bundleName, resolveRecursively, recursionLevel); // if LocalStrings File does not exist -> return error msg on screen // / fallback to default language if (properties == null) { if (Settings.isDebuging()) { log.warn(FILE_NOT_FOUND_ERROR_PREFIX + "! locale::" + locale.toString() + ", path::" + bundleName, null); } } else { msg = properties.getProperty(key); } } // The following fallback behaviour is similar to // java.util.ResourceBundle if (msg == null) { if (log.isDebug()) { log.debug("Key::" + key + " not found for bundle::" + bundleName + " and locale::" + locale.toString(), null); } // Fallback on the language if the locale has a country and/or a // variant // de_DE_variant -> de_DE -> de // Only after having all those checked we will fallback to the // default language // 1. Check on variant String variant = locale.getVariant(); if (!variant.equals("")) { Locale newLoc = I18nModule.getAllLocales().get(locale.getLanguage() + "_" + locale.getCountry()); if (newLoc != null) msg = getLocalizedString(bundleName, key, args, newLoc, overlayEnabled, false, fallBackToFallbackLocale, resolveRecursively, recursionLevel); } if (msg == null) { // 2. Check on country String country = locale.getCountry(); if (!country.equals("")) { Locale newLoc = I18nModule.getAllLocales().get(locale.getLanguage()); if (newLoc != null) msg = getLocalizedString(bundleName, key, args, newLoc, overlayEnabled, false, fallBackToFallbackLocale, resolveRecursively, recursionLevel); } // else we have an original locale with only a language given -> // no language specific fallbacks anymore } } if (msg == null) { // Message still empty? Use fallback to default language? // yes: return the call applied with the olatcore default locale // no: return null to indicate nothing was found so that callers may // use fallbacks if (fallBackToDefaultLocale) { return getLocalizedString(bundleName, key, args, I18nModule.getDefaultLocale(), overlayEnabled, false, fallBackToFallbackLocale, resolveRecursively, recursionLevel); } else { if (fallBackToFallbackLocale) { // fallback to fallback locale Locale fallbackLocale = I18nModule.getFallbackLocale(); if (fallbackLocale.equals(locale)) { // finish when when already in fallback locale if (isLogDebugEnabled()) { logWarn("Could not find translation for bundle::" + bundleName + " and key::" + key + " ; not even in default or fallback packages", null); } return null; } else { return getLocalizedString(bundleName, key, args, fallbackLocale, overlayEnabled, false, false, resolveRecursively, recursionLevel); } } else { return null; } } } // When caching not enabled we need to check for keys contained in this // value. In caching mode this is already done while loading the // properties // file if (resolveRecursively && (!cachingEnabled || properties != null)) { msg = resolveValuesInternalKeys(locale, bundleName, key, properties, overlayEnabled, recursionLevel, msg); } // Add markup code to identify translated strings if (allowDecoration && isCurrentThreadMarkLocalizedStringsEnabled() && !bundleName.startsWith(BUNDLE_INLINE_TRANSLATION_INTERCEPTOR) && !bundleName.startsWith(BUNDLE_EXCEPTION) && isInlineTranslationEnabledForKey(bundleName, key)) { // identifyer consists of bundle name and key and an id to // distinguish multiple translations of the same key String identifyer = bundleName + ":" + key + ":" + CodeHelper.getRAMUniqueID(); msg = IDENT_PREFIX + identifyer + IDENT_START_POSTFIX + msg + IDENT_PREFIX + identifyer + IDENT_END_POSTFIX; } // Add the the {0},{1} arguments to the GUI message if (args == null) { return msg; } else { // Escape single quotes with single quotes. Single quotes have special meaning in MessageFormat // See OLAT-5107, OLAT-5756 if (msg.indexOf("'") > -1) { msg = msg.replaceAll("'", "''"); } return MessageFormat.format(msg, args); } }
From source file:org.apache.openjpa.jdbc.sql.DBDictionary.java
/** * Set the given value as a parameter to the statement. *///from w ww . jav a2 s . com public void setLocale(PreparedStatement stmnt, int idx, Locale val, Column col) throws SQLException { setString(stmnt, idx, val.getLanguage() + "_" + val.getCountry() + "_" + val.getVariant(), col); }
From source file:com.salesmanager.common.ShopInterceptor.java
public String baseIntercept(ActionInvocation invoke, HttpServletRequest req, HttpServletResponse resp) throws Exception { Locale locale = LocaleUtil.getLocale(req); MerchantStore mStore = SessionUtil.getMerchantStore(req); // languages/*ww w .j a v a2 s . co m*/ Map<Integer, List> customPortletsMap = null; CacheModule cache = (CacheModule) SpringUtil.getBean("cache"); ReferenceService rservice = (ReferenceService) ServiceFactory.getService(ServiceFactory.ReferenceService); ConfigurationResponse vo = null; try { vo = (ConfigurationResponse) cache.getFromCache(Constants.CACHE_CONFIGURATION, mStore); } catch (Exception ignore) { } if (vo == null) { /** * MERCHANT CONFIGURATION */ ConfigurationRequest request = new ConfigurationRequest(mStore.getMerchantId());// get all configurations MerchantService mservice = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService); vo = mservice.getConfiguration(request); if (vo != null) { try { cache.putInCache(Constants.CACHE_CONFIGURATION, vo, Constants.CACHE_CONFIGURATION, mStore); } catch (Exception e) { log.error(e); } } } ShippingType shippingType = null; String shippingModule = null;// will determine shipping company name String shippingRegionLine = null; String shippingEstimateLine = null; if (vo != null && vo.getMerchantConfigurationList() != null && vo.getMerchantConfigurationList().size() > 0) { List configurations = vo.getMerchantConfigurationList(); Iterator i = configurations.iterator(); Map confMap = new HashMap(); Collection prtList = new ArrayList(); while (i.hasNext()) { MerchantConfiguration conf = (MerchantConfiguration) i.next(); if (conf.getConfigurationKey().equals(ConfigurationConstants.STORE_PORTLETS_)) { Collection portletsList = MerchantConfigurationUtil .getConfigurationList(conf.getConfigurationValue(), ";"); if (portletsList != null && portletsList.size() > 0) { Iterator ii = portletsList.iterator(); while (ii.hasNext()) { String p = (String) ii.next(); PortletConfiguration pc = (PortletConfiguration) confMap.get(p); if (pc == null) { pc = new PortletConfiguration(); pc.setModuleName(p); confMap.put(p, p); } prtList.add(pc); } } req.setAttribute("STORE_FRONT_PORTLETS_MAP", confMap);//this one is used by tag lib for getting portlet configuration req.setAttribute("STORE_FRONT_PORTLETS", prtList); continue; } else if (conf.getConfigurationKey().equals(ConfigurationConstants.G_API)) { if (!StringUtils.isBlank(conf.getConfigurationValue())) { req.setAttribute("ANALYTICS", conf.getConfigurationValue()); } if (!StringUtils.isBlank(conf.getConfigurationValue1())) { req.setAttribute("G_API", conf.getConfigurationValue1()); } continue; } else if (conf.getConfigurationKey() .equals(ShippingConstants.MODULE_SHIPPING_RT_MODULE_INDIC_NAME)) { if (!StringUtils.isBlank(conf.getConfigurationValue1())) { shippingModule = conf.getConfigurationValue1(); } continue; } else if (conf.getConfigurationKey() .equals(ShippingConstants.MODULE_SHIPPING_INDIC_COUNTRIES_COSTS)) { if (!StringUtils.isBlank(conf.getConfigurationValue()) && conf.getConfigurationValue().equals("true")) { if (!StringUtils.isBlank(conf.getConfigurationValue1())) { shippingRegionLine = conf.getConfigurationValue1(); } } continue; } else if (conf.getConfigurationKey().equals(ShippingConstants.MODULE_SHIPPING_ESTIMATE_BYCOUNTRY)) { if (!StringUtils.isBlank(conf.getConfigurationValue1())) { shippingEstimateLine = conf.getConfigurationValue1(); } continue; } else if (conf.getConfigurationKey().equals(ShippingConstants.MODULE_SHIPPING_ZONES_SHIPPING)) { if (!StringUtils.isBlank(conf.getConfigurationValue())) { if (ShippingConstants.INTERNATIONAL_SHIPPING.equals(conf.getConfigurationValue())) { shippingType = ShippingType.INTERNATIONAL; } else if (ShippingConstants.DOMESTIC_SHIPPING.equals(conf.getConfigurationValue())) { shippingType = ShippingType.NATIONAL; } } continue; } } // end while ShippingEstimate estimate = new ShippingEstimate(); estimate.setLocale(locale); estimate.setCurrency(mStore.getCurrency()); estimate.setShippingType(shippingType); estimate.setShippingModule(shippingModule); if (!StringUtils.isBlank(shippingRegionLine)) { Map m = ShippingUtil.buildShippingPriceRegionMap("", shippingRegionLine, shippingEstimateLine); estimate.setRegions(m); } String currentCountryIsoCode = locale.getCountry(); CountryDescription zoneDescription = rservice.getCountryDescriptionByIsoCode(currentCountryIsoCode, LanguageUtil.getLanguageNumberCode(locale.getLanguage())); CountryDescription storeZoneDescription = rservice.getCountryDescriptionByCountryId(mStore.getCountry(), LanguageUtil.getLanguageNumberCode(locale.getLanguage())); if (zoneDescription != null) { estimate.setCustomerCountry(zoneDescription.getCountryName()); } estimate.setStoreCountry(storeZoneDescription.getCountryName()); if (!StringUtils.isBlank(shippingModule)) { CoreModuleService cms = rservice.getCoreModuleService(currentCountryIsoCode, shippingModule); if (cms != null) { estimate.setShippingCompanyLogo(cms.getCoreModuleServiceLogoPath()); } } // iterate and get the index if (!StringUtils.isBlank(shippingRegionLine)) { StringTokenizer cvtk = new StringTokenizer(shippingRegionLine, "|"); int index = 1; boolean countryFound = false; while (cvtk.hasMoreTokens() && !countryFound) { String countryline = cvtk.nextToken();// maxpound:price,maxpound:price...| if (!countryline.equals("*")) { StringTokenizer countrystk = new StringTokenizer(countryline, ";"); String country = null; while (countrystk.hasMoreTokens()) { country = countrystk.nextToken(); if (currentCountryIsoCode != null && country.equals(currentCountryIsoCode)) { estimate.setCustomerZoneIndex(index); countryFound = true; break; } } } index++; } } /** * Labels required for the * Custom portlets SECTION 75 * Shipping fees 02 * Custom page links 70 * Since those are displayed on each page, need to get them on each request */ Collection<DynamicLabel> dynamicLabels = null; try { dynamicLabels = (Collection) cache.getFromCache(Constants.CACHE_LABELS + "_" + LabelConstants.STORE_FRONT_CUSTOM_PORTLETS + "_" + locale.getLanguage(), mStore); } catch (Exception ignore) { } if (dynamicLabels == null) { // get from missed boolean missed = false; try { missed = (Boolean) cache.getFromCache(Constants.CACHE_LABELS + "_" + LabelConstants.STORE_FRONT_CUSTOM_PORTLETS + "_MISSED_" + locale.getLanguage(), mStore); } catch (Exception ignore) { } if (!missed) { // get all dynamic labels // get shipping, custom portlets, custom pages [section_id in] List sections = new ArrayList(); sections.add(LabelConstants.SHIPPING_FEES_SECTION); sections.add(LabelConstants.STORE_FRONT_CUSTOM_PAGES); sections.add(LabelConstants.STORE_FRONT_CUSTOM_PORTLETS); dynamicLabels = rservice.getDynamicLabels(mStore.getMerchantId(), sections, locale); if (dynamicLabels != null && dynamicLabels.size() > 0) { try { cache.putInCache(Constants.CACHE_LABELS + "_" + LabelConstants.STORE_FRONT_CUSTOM_PORTLETS + "_" + locale.getLanguage(), dynamicLabels, Constants.CACHE_LABELS, mStore); } catch (Exception e) { log.error(e); } } else { try { cache.putInCache( Constants.CACHE_LABELS + "_" + LabelConstants.STORE_FRONT_CUSTOM_PORTLETS + "_MISSED_" + locale.getLanguage(), true, Constants.CACHE_LABELS, mStore); } catch (Exception e) { log.error(e); } } } // end missed } if (dynamicLabels != null && dynamicLabels.size() > 0) { Iterator it = dynamicLabels.iterator(); List topNavList = new ArrayList(); List customPortlets = new ArrayList(); while (it.hasNext()) { DynamicLabel dl = (DynamicLabel) it.next(); if (dl.getSectionId() == LabelConstants.SHIPPING_FEES_SECTION) { estimate.setDefaultShippingEstimateText( dl.getDynamicLabelDescription().getDynamicLabelDescription()); continue; } // custom pages if (dl.getSectionId() == LabelConstants.STORE_FRONT_CUSTOM_PAGES) { topNavList.add(dl); continue; } // custom portlets // set in a map [title, dl] if (dl.getSectionId() == LabelConstants.STORE_FRONT_CUSTOM_PORTLETS) { if (dl.isVisible()) { if (customPortletsMap == null) { customPortletsMap = new HashMap(); } PortletConfiguration pc = new PortletConfiguration(); pc.setContent(dl.getDynamicLabelDescription().getDynamicLabelDescription()); pc.setCustom(true); pc.setPosition(dl.getPosition()); pc.setModuleName(dl.getTitle()); List portlets = customPortletsMap.get(dl.getPosition()); if (portlets == null) { portlets = new ArrayList(); customPortletsMap.put(dl.getPosition(), portlets); } portlets.add(pc); } continue; } } if (topNavList.size() > 0) { req.setAttribute("TOPNAV", topNavList); } if (customPortletsMap.size() > 0) { req.setAttribute("CUSTOMPORTLETS", customPortletsMap); } } req.setAttribute("SHIPPING", estimate); } // end if Object o = invoke.getAction(); if (o instanceof SalesManagerBaseAction) { SalesManagerBaseAction action = ((SalesManagerBaseAction) invoke.getAction()); action.setPageTitle(mStore.getStorename()); } /** set objects in request **/ Customer customer = SessionUtil.getCustomer(req); if (customer != null) { req.setAttribute("CUSTOMER", customer); } req.setAttribute("merchantId", mStore.getMerchantId()); /** * Messages */ String errMessage = MessageUtil.getErrorMessage(req); if (!StringUtils.isBlank(errMessage)) { SalesManagerBaseAction action = (SalesManagerBaseAction) invoke.getAction(); action.addActionError(errMessage); } String message = MessageUtil.getMessage(req); if (!StringUtils.isBlank(message)) { SalesManagerBaseAction action = (SalesManagerBaseAction) invoke.getAction(); action.addActionMessage(message); } MessageUtil.resetMessages(req); // do common stuff String r = doIntercept(invoke, req, resp); return r; }
From source file:org.apache.maven.plugin.javadoc.AbstractJavadocMojo.java
/** * Checks for the validity of the Javadoc options used by the user. * * @throws MavenReportException if error */// ww w . j a v a2 s.com private void validateJavadocOptions() throws MavenReportException { // encoding if (StringUtils.isNotEmpty(getEncoding()) && !JavadocUtil.validateEncoding(getEncoding())) { throw new MavenReportException("Unsupported option <encoding/> '" + getEncoding() + "'"); } // locale if (StringUtils.isNotEmpty(this.locale)) { StringTokenizer tokenizer = new StringTokenizer(this.locale, "_"); final int maxTokens = 3; if (tokenizer.countTokens() > maxTokens) { throw new MavenReportException( "Unsupported option <locale/> '" + this.locale + "', should be language_country_variant."); } Locale localeObject = null; if (tokenizer.hasMoreTokens()) { String language = tokenizer.nextToken().toLowerCase(Locale.ENGLISH); if (!Arrays.asList(Locale.getISOLanguages()).contains(language)) { throw new MavenReportException( "Unsupported language '" + language + "' in option <locale/> '" + this.locale + "'"); } localeObject = new Locale(language); if (tokenizer.hasMoreTokens()) { String country = tokenizer.nextToken().toUpperCase(Locale.ENGLISH); if (!Arrays.asList(Locale.getISOCountries()).contains(country)) { throw new MavenReportException( "Unsupported country '" + country + "' in option <locale/> '" + this.locale + "'"); } localeObject = new Locale(language, country); if (tokenizer.hasMoreTokens()) { String variant = tokenizer.nextToken(); localeObject = new Locale(language, country, variant); } } } if (localeObject == null) { throw new MavenReportException( "Unsupported option <locale/> '" + this.locale + "', should be language_country_variant."); } this.locale = localeObject.toString(); final List<Locale> availableLocalesList = Arrays.asList(Locale.getAvailableLocales()); if (StringUtils.isNotEmpty(localeObject.getVariant()) && !availableLocalesList.contains(localeObject)) { StringBuilder sb = new StringBuilder(); sb.append("Unsupported option <locale/> with variant '").append(this.locale); sb.append("'"); localeObject = new Locale(localeObject.getLanguage(), localeObject.getCountry()); this.locale = localeObject.toString(); sb.append(", trying to use <locale/> without variant, i.e. '").append(this.locale).append("'"); if (getLog().isWarnEnabled()) { getLog().warn(sb.toString()); } } if (!availableLocalesList.contains(localeObject)) { throw new MavenReportException("Unsupported option <locale/> '" + this.locale + "'"); } } }