List of usage examples for javax.servlet.http HttpSession invalidate
public void invalidate();
From source file:com.liferay.portal.events.ServicePreAction.java
public ThemeDisplay initThemeDisplay(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); // Company/*from w ww.j a v a 2 s. co m*/ Company company = PortalUtil.getCompany(request); long companyId = company.getCompanyId(); // CDN host String cdnHost = PortalUtil.getCDNHost(request); String dynamicResourcesCDNHost = StringPool.BLANK; boolean cdnDynamicResourceEnabled = PortalUtil.isCDNDynamicResourcesEnabled(request); if (cdnDynamicResourceEnabled) { dynamicResourcesCDNHost = 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 = dynamicResourcesCDNHost.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(WebServerServletTokenUtil.getToken(company.getLogoId())); String companyLogo = sb.toString(); int companyLogoHeight = 0; int companyLogoWidth = 0; Image companyLogoImage = ImageLocalServiceUtil.getCompanyLogo(company.getLogoId()); if (companyLogoImage != null) { companyLogoHeight = companyLogoImage.getHeight(); 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 null; } boolean signedIn = false; if (user == null) { user = company.getDefaultUser(); } else if (!user.isDefaultUser()) { signedIn = true; } if (PropsValues.BROWSER_CACHE_DISABLED || (PropsValues.BROWSER_CACHE_SIGNED_IN_DISABLED && signedIn)) { response.setDateHeader(HttpHeaders.EXPIRES, 0); response.setHeader(HttpHeaders.CACHE_CONTROL, HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE); response.setHeader(HttpHeaders.PRAGMA, HttpHeaders.PRAGMA_NO_CACHE_VALUE); } 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"); if (LayoutLocalServiceUtil.fetchLayout(refererPlid) == null) { refererPlid = 0; } String controlPanelCategory = ParamUtil.getString(request, "controlPanelCategory"); // Permission checker PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user); PermissionThreadLocal.setPermissionChecker(permissionChecker); //Modification start (code changed and moved to the bottom) // 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, false); if (Validator.isNotNull(languageId)) { locale = LocaleUtil.fromLanguageId(languageId); } // Get locale from the request if ((locale == null) && PropsValues.LOCALE_DEFAULT_REQUEST) { Enumeration<Locale> locales = request.getLocales(); while (locales.hasMoreElements()) { Locale requestLocale = locales.nextElement(); if (Validator.isNull(requestLocale.getCountry())) { // Locales must contain a country code requestLocale = LanguageUtil.getLocale( requestLocale.getLanguage()); } if (LanguageUtil.isAvailableLocale(requestLocale)) { locale = requestLocale; break; } } } // 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); }*/ //Modification end // 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); long sourceGroupId = ParamUtil.getLong(request, "p_v_l_s_g_id"); if ((sourceGroupId > 0) && (sourceGroupId != layout.getGroupId())) { Group sourceGroup = GroupLocalServiceUtil.getGroup(sourceGroupId); if (layout.isPublicLayout() || SitesUtil.isUserGroupLayoutSetViewable(permissionChecker, layout.getGroup())) { layout = new VirtualLayout(layout, sourceGroup); } else { layout = null; } } } 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); } } Boolean redirectToDefaultLayout = (Boolean) request.getAttribute(WebKeys.REDIRECT_TO_DEFAULT_LAYOUT); if (redirectToDefaultLayout == null) { redirectToDefaultLayout = Boolean.FALSE; } if (layout != null) { Group group = layout.getGroup(); if (!signedIn && PropsValues.AUTH_FORWARD_BY_REDIRECT) { request.setAttribute(WebKeys.REQUESTED_LAYOUT, layout); } String ppid = ParamUtil.getString(request, "p_p_id"); if (Validator.isNull(controlPanelCategory) && Validator.isNotNull(ppid) && (LiferayWindowState.isPopUp(request) || LiferayWindowState.isExclusive(request))) { controlPanelCategory = _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + ppid; } boolean viewableGroup = LayoutPermissionUtil.contains(permissionChecker, layout, controlPanelCategory, true, ActionKeys.VIEW); boolean viewableStaging = GroupPermissionUtil.contains(permissionChecker, group.getGroupId(), ActionKeys.VIEW_STAGING); if (viewableStaging) { layouts = LayoutLocalServiceUtil.getLayouts(layout.getGroupId(), layout.isPrivateLayout(), LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); } else if (!viewableGroup && group.isStagingGroup()) { layout = null; } else /* Permissions are managed by Mobile Portlet if (!isLoginRequest(request) && (!viewableGroup || (!redirectToDefaultLayout && !LayoutPermissionUtil.contains( permissionChecker, layout, false, ActionKeys.VIEW)))) { if (user.isDefaultUser() && PropsValues.AUTH_LOGIN_PROMPT_ENABLED) { throw new PrincipalException("User is not authenticated"); } 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 NoSuchLayoutException(sb.toString()); } else*/ if (isLoginRequest(request) && !viewableGroup) { 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; } } } List<Layout> unfilteredLayouts = layouts; 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); LayoutSet layoutSet = null; boolean hasCustomizeLayoutPermission = false; boolean hasUpdateLayoutPermission = false; boolean customizedView = SessionParamUtil.getBoolean(request, "customized_view", true); if (layout != null) { hasCustomizeLayoutPermission = LayoutPermissionUtil.contains(permissionChecker, layout, ActionKeys.CUSTOMIZE); hasUpdateLayoutPermission = LayoutPermissionUtil.contains(permissionChecker, layout, ActionKeys.UPDATE); layoutSet = layout.getLayoutSet(); if (company.isSiteLogo()) { long logoId = 0; if (layoutSet.isLogo()) { logoId = layoutSet.getLogoId(); if (logoId == 0) { logoId = layoutSet.getLiveLogoId(); } } 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(WebServerServletTokenUtil.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) layout.clone(); layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType(); boolean customizable = layoutTypePortlet.isCustomizable(); if (!customizable || (group.isLayoutPrototype() || group.isLayoutSetPrototype())) { customizedView = false; } layoutTypePortlet.setCustomizedView(customizedView); layoutTypePortlet.setUpdatePermission(hasUpdateLayoutPermission); if (signedIn && customizable && customizedView && hasCustomizeLayoutPermission) { PortalPreferences portalPreferences = PortletPreferencesFactoryUtil.getPortalPreferences(companyId, user.getUserId(), true); layoutTypePortlet.setPortalPreferences(portalPreferences); } LayoutClone layoutClone = LayoutCloneFactory.getInstance(); if (layoutClone != null) { String typeSettings = layoutClone.get(request, plid); if (typeSettings != null) { UnicodeProperties typeSettingsProperties = new UnicodeProperties(true); typeSettingsProperties.load(typeSettings); String stateMax = typeSettingsProperties.getProperty(LayoutTypePortletConstants.STATE_MAX); String stateMin = typeSettingsProperties.getProperty(LayoutTypePortletConstants.STATE_MIN); String modeAbout = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_ABOUT); String modeConfig = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_CONFIG); String modeEdit = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_EDIT); String modeEditDefaults = typeSettingsProperties .getProperty(LayoutTypePortletConstants.MODE_EDIT_DEFAULTS); String modeEditGuest = typeSettingsProperties .getProperty(LayoutTypePortletConstants.MODE_EDIT_GUEST); String modeHelp = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_HELP); String modePreview = typeSettingsProperties .getProperty(LayoutTypePortletConstants.MODE_PREVIEW); String modePrint = typeSettingsProperties.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); } // Scope long scopeGroupId = PortalUtil.getScopeGroupId(request); if ((scopeGroupId <= 0) && (doAsGroupId > 0)) { scopeGroupId = doAsGroupId; } long parentGroupId = PortalUtil.getParentGroupId(scopeGroupId); // 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); } 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"); lifecycle = ParamUtil.getString(request, "p_t_lifecycle", lifecycle); 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(); } ////////// Modification start ////////// // Locale Locale locale = null; String[] languageIds = request.getParameterMap().get("languageId"); if (languageIds != null && languageIds.length > 0 && StringUtils.isNotEmpty(languageIds[0])) { Locale localeFromLanguageId = LocaleUtil.fromLanguageId(languageIds[0]); session.setAttribute(Globals.LOCALE_KEY, localeFromLanguageId); } try { locale = (Locale) session.getAttribute(Globals.LOCALE_KEY); } catch (IllegalStateException e) { _log.warn("Can't get locale from session, session is invalidated"); } 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); } if (locale == null) { locale = LanguageDetectionUtil.detectLocale(request); } ////////// Modification end ////////// // Theme display ThemeDisplay themeDisplay = ThemeDisplayFactory.create(); //Modification start // themeDisplay.setHttpServletRequest(request); //Modification end // Set the CDN host, portal URL, and Facebook application ID first // because other methods (setLookAndFeel) depend on them being set themeDisplay.setCDNHost(cdnHost); themeDisplay.setCDNDynamicResourcesHost(dynamicResourcesCDNHost); 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.setControlPanelCategory(controlPanelCategory); themeDisplay.setLayoutSet(layoutSet); themeDisplay.setLayoutSetLogo(layoutSetLogo); themeDisplay.setLayout(layout); themeDisplay.setLayouts(layouts); themeDisplay.setUnfilteredLayouts(unfilteredLayouts); 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(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(contextPath.concat("/html/js")); themeDisplay.setPathMain(mainPath); themeDisplay.setPathSound(contextPath.concat("/html/sound")); // Icons themeDisplay.setShowAddContentIcon(false); themeDisplay.setShowControlPanelIcon(signedIn); themeDisplay.setShowHomeIcon(true); themeDisplay.setShowMyAccountIcon(signedIn); themeDisplay.setShowPageSettingsIcon(false); themeDisplay.setShowPortalIcon(true); themeDisplay.setShowSignInIcon(!signedIn); themeDisplay.setShowSignOutIcon(signedIn); boolean showSiteContentIcon = false; long controlPanelPlid = 0; if (signedIn) { Group controlPanelGroup = GroupLocalServiceUtil.getGroup(companyId, GroupConstants.CONTROL_PANEL); controlPanelPlid = LayoutLocalServiceUtil.getDefaultPlid(controlPanelGroup.getGroupId(), true); List<Portlet> siteContentPortlets = PortalUtil.getControlPanelPortlets(PortletCategoryKeys.CONTENT, themeDisplay); Portlet groupPagesPortlet = PortletLocalServiceUtil.getPortletById(PortletKeys.GROUP_PAGES); siteContentPortlets.remove(groupPagesPortlet); Portlet siteMembershipsAdminPortlet = PortletLocalServiceUtil .getPortletById(PortletKeys.SITE_MEMBERSHIPS_ADMIN); siteContentPortlets.remove(siteMembershipsAdminPortlet); Portlet siteSettingsPortlet = PortletLocalServiceUtil.getPortletById(PortletKeys.SITE_SETTINGS); siteContentPortlets.remove(siteSettingsPortlet); showSiteContentIcon = PortletPermissionUtil.contains(permissionChecker, scopeGroupId, controlPanelPlid, siteContentPortlets, ActionKeys.VIEW); } themeDisplay.setShowSiteContentIcon(showSiteContentIcon); themeDisplay.setShowStagingIcon(false); // Session if (PropsValues.SESSION_ENABLE_URL_WITH_SESSION_ID && !CookieKeys.hasSessionId(request)) { themeDisplay.setAddSessionIdToURL(true); themeDisplay.setSessionId(session.getId()); } // URLs 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); } if (themeDisplay.isAddSessionIdToURL()) { urlControlPanel = PortalUtil.getURLWithSessionId(urlControlPanel, session.getId()); } themeDisplay.setURLControlPanel(urlControlPanel); String siteContentURL = urlControlPanel; siteContentURL = HttpUtil.addParameter(siteContentURL, "controlPanelCategory", PortletCategoryKeys.CONTENT); themeDisplay.setURLSiteContent(siteContentURL); 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); if (hasUpdateLayoutPermission) { themeDisplay.setShowAddContentIconPermission(true); if (!LiferayWindowState.isMaximized(request)) { themeDisplay.setShowAddContentIcon(true); } themeDisplay.setShowLayoutTemplatesIcon(true); if (!group.isUser()) { themeDisplay.setShowPageCustomizationIcon(true); } themeDisplay.setURLAddContent("Liferay.LayoutConfiguration.toggle('" .concat(PortletKeys.LAYOUT_CONFIGURATION).concat("');")); themeDisplay.setURLLayoutTemplates("Liferay.LayoutConfiguration.showTemplates();"); } if (hasCustomizeLayoutPermission && customizedView) { themeDisplay.setShowAddContentIconPermission(true); if (!LiferayWindowState.isMaximized(request)) { themeDisplay.setShowAddContentIcon(true); } themeDisplay.setURLAddContent("Liferay.LayoutConfiguration.toggle('" .concat(PortletKeys.LAYOUT_CONFIGURATION).concat("');")); } } if (hasUpdateLayoutPermission) { themeDisplay.setShowPageSettingsIcon(true); LiferayPortletURL pageSettingsURL = new PortletURLImpl(request, PortletKeys.LAYOUTS_ADMIN, controlPanelPlid, PortletRequest.RENDER_PHASE); pageSettingsURL.setControlPanelCategory( _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + PortletKeys.LAYOUTS_ADMIN); pageSettingsURL.setDoAsGroupId(scopeGroupId); pageSettingsURL.setParameter("struts_action", "/layouts_admin/edit_layouts"); if (layout.isPrivateLayout()) { pageSettingsURL.setParameter("tabs1", "private-pages"); } else { pageSettingsURL.setParameter("tabs1", "public-pages"); } pageSettingsURL.setParameter("closeRedirect", currentURL); pageSettingsURL.setParameter("groupId", String.valueOf(scopeGroupId)); pageSettingsURL.setParameter("selPlid", String.valueOf(plid)); pageSettingsURL.setPortletMode(PortletMode.VIEW); pageSettingsURL.setWindowState(LiferayWindowState.POP_UP); themeDisplay.setURLPageSettings(pageSettingsURL); boolean site = group.isSite(); if (!site && group.isStagingGroup()) { Group liveGroup = group.getLiveGroup(); site = liveGroup.isSite(); } if (site && GroupPermissionUtil.contains(permissionChecker, scopeGroupId, ActionKeys.ASSIGN_MEMBERS)) { themeDisplay.setShowManageSiteMembershipsIcon(true); LiferayPortletURL manageSiteMembershipsURL = new PortletURLImpl(request, PortletKeys.SITE_MEMBERSHIPS_ADMIN, controlPanelPlid, PortletRequest.RENDER_PHASE); manageSiteMembershipsURL.setControlPanelCategory( _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + PortletKeys.SITE_MEMBERSHIPS_ADMIN); manageSiteMembershipsURL.setDoAsGroupId(scopeGroupId); manageSiteMembershipsURL.setParameter("struts_action", "/sites_admin/edit_site_assignments"); manageSiteMembershipsURL.setParameter("groupId", String.valueOf(scopeGroupId)); manageSiteMembershipsURL.setParameter("selPlid", String.valueOf(plid)); manageSiteMembershipsURL.setPortletMode(PortletMode.VIEW); manageSiteMembershipsURL.setWindowState(LiferayWindowState.POP_UP); themeDisplay.setURLManageSiteMemberships(manageSiteMembershipsURL); } else { themeDisplay.setShowManageSiteMembershipsIcon(false); } } boolean hasAddLayoutGroupPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId, ActionKeys.ADD_LAYOUT); boolean hasAddLayoutLayoutPermission = LayoutPermissionUtil.contains(permissionChecker, layout, ActionKeys.ADD_LAYOUT); boolean hasManageLayoutsGroupPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId, ActionKeys.MANAGE_LAYOUTS); boolean hasManageStagingPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId, ActionKeys.MANAGE_STAGING); boolean hasPublishStagingPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId, ActionKeys.PUBLISH_STAGING); boolean hasUpdateGroupPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId, ActionKeys.UPDATE); boolean hasViewStagingPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId, ActionKeys.VIEW_STAGING); if (!group.isControlPanel() && !group.isUser() && !group.isUserGroup() && hasUpdateGroupPermission) { themeDisplay.setShowSiteSettingsIcon(true); LiferayPortletURL siteSettingsURL = new PortletURLImpl(request, PortletKeys.SITE_SETTINGS, controlPanelPlid, PortletRequest.RENDER_PHASE); siteSettingsURL.setControlPanelCategory( _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + PortletKeys.SITE_SETTINGS); siteSettingsURL.setDoAsGroupId(scopeGroupId); siteSettingsURL.setParameter("struts_action", "/sites_admin/edit_site"); siteSettingsURL.setParameter("closeRedirect", currentURL); siteSettingsURL.setParameter("groupId", String.valueOf(scopeGroupId)); siteSettingsURL.setPortletMode(PortletMode.VIEW); siteSettingsURL.setWindowState(LiferayWindowState.POP_UP); themeDisplay.setURLSiteSettings(siteSettingsURL); } if (!group.isLayoutPrototype() && (hasAddLayoutGroupPermission || hasAddLayoutLayoutPermission || hasManageLayoutsGroupPermission || hasUpdateGroupPermission)) { themeDisplay.setShowSiteMapSettingsIcon(true); LiferayPortletURL siteMapSettingsURL = new PortletURLImpl(request, PortletKeys.LAYOUTS_ADMIN, controlPanelPlid, PortletRequest.RENDER_PHASE); siteMapSettingsURL.setControlPanelCategory( _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + PortletKeys.LAYOUTS_ADMIN); siteMapSettingsURL.setDoAsGroupId(scopeGroupId); siteMapSettingsURL.setParameter("struts_action", "/layouts_admin/edit_layouts"); if (layout.isPrivateLayout()) { siteMapSettingsURL.setParameter("tabs1", "private-pages"); } else { siteMapSettingsURL.setParameter("tabs1", "public-pages"); } siteMapSettingsURL.setParameter("closeRedirect", currentURL); siteMapSettingsURL.setParameter("groupId", String.valueOf(scopeGroupId)); siteMapSettingsURL.setPortletMode(PortletMode.VIEW); siteMapSettingsURL.setWindowState(LiferayWindowState.POP_UP); themeDisplay.setURLSiteMapSettings(siteMapSettingsURL); } 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()) { if (hasManageStagingPermission || hasPublishStagingPermission || hasUpdateLayoutPermission || hasViewStagingPermission) { themeDisplay.setShowStagingIcon(true); } if (hasPublishStagingPermission) { PortletURL publishToLiveURL = new PortletURLImpl(request, PortletKeys.LAYOUTS_ADMIN, plid, PortletRequest.RENDER_PHASE); publishToLiveURL.setParameter("struts_action", "/layouts_admin/publish_layouts"); 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)); publishToLiveURL.setPortletMode(PortletMode.VIEW); publishToLiveURL.setWindowState(LiferayWindowState.EXCLUSIVE); themeDisplay.setURLPublishToLive(publishToLiveURL); } } PortletURLImpl myAccountURL = new PortletURLImpl(request, PortletKeys.MY_ACCOUNT, controlPanelPlid, PortletRequest.RENDER_PHASE); if (scopeGroupId > 0) { myAccountURL.setDoAsGroupId(scopeGroupId); } myAccountURL.setParameter("struts_action", "/my_account/edit_user"); myAccountURL.setPortletMode(PortletMode.VIEW); if (refererPlid > 0) { myAccountURL.setRefererPlid(refererPlid); } else { myAccountURL.setRefererPlid(plid); } myAccountURL.setWindowState(WindowState.MAXIMIZED); 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 (layout.isLayoutPrototypeLinkActive()) { themeDisplay.setShowPageCustomizationIcon(false); } if (group.isLayoutPrototype()) { themeDisplay.setShowControlPanelIcon(false); themeDisplay.setShowHomeIcon(false); themeDisplay.setShowManageSiteMembershipsIcon(false); themeDisplay.setShowMyAccountIcon(false); themeDisplay.setShowPageCustomizationIcon(false); themeDisplay.setShowPageSettingsIcon(true); themeDisplay.setShowPortalIcon(false); themeDisplay.setShowSignInIcon(false); themeDisplay.setShowSignOutIcon(false); themeDisplay.setShowSiteContentIcon(false); themeDisplay.setShowSiteSettingsIcon(false); themeDisplay.setShowStagingIcon(false); } if (group.isLayoutSetPrototype()) { themeDisplay.setShowPageCustomizationIcon(false); themeDisplay.setShowSiteSettingsIcon(false); } if (group.hasStagingGroup() && !group.isStagingGroup()) { themeDisplay.setShowLayoutTemplatesIcon(false); themeDisplay.setShowPageCustomizationIcon(false); themeDisplay.setShowPageSettingsIcon(false); themeDisplay.setShowSiteContentIcon(false); themeDisplay.setShowSiteMapSettingsIcon(false); themeDisplay.setShowSiteSettingsIcon(false); } themeDisplay.setURLPortal(portalURL.concat(contextPath)); String urlSignIn = mainPath.concat("/portal/login"); 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.setParameter("struts_action", "/update_manager/view"); updateManagerURL.setPortletMode(PortletMode.VIEW); updateManagerURL.setWindowState(WindowState.MAXIMIZED); themeDisplay.setURLUpdateManager(updateManagerURL); return themeDisplay; }
From source file:com.funambol.email.content.ContentProviderServlet.java
/** * * @param request/*from w w w . j av a 2s. co m*/ * @param response * @throws java.io.IOException */ private void replyAttachment(HttpServletRequest request, HttpServletResponse response) throws IOException { ContentProviderManager contentServiceManager = new ContentProviderManager(); HttpSession session = request.getSession(); try { if (log.isTraceEnabled()) { log.trace("Start Handling request."); } String authToken = request.getParameter(PARAMETER_AUTH); if (authToken == null || "".equals(authToken)) { printErrorPage(request, response, "The authorization parameter is empty", null); return; } if (log.isTraceEnabled()) { log.trace("Authorization token: " + authToken); } String username = request.getParameter(PARAMETER_USER); if (username == null || "".equals(username)) { printErrorPage(request, response, "The user name parameter is empty", null); return; } if (log.isTraceEnabled()) { log.trace("User name: " + username); } String attachIdx = request.getParameter(PARAMETER_INDEX); if (attachIdx == null || "".equals(attachIdx)) { printErrorPage(request, response, "The attachment index parameter is empty", null); return; } int attachmentIndex = 0; try { attachmentIndex = Integer.parseInt(attachIdx); } catch (NumberFormatException ex) { printErrorPage(request, response, "Parameter \"attachment index\" must be a valid number", null); return; } if (log.isTraceEnabled()) { log.trace("Attachment index: " + attachmentIndex); } MailServerAccount mailServerAccount = contentServiceManager.retrieveMailServerAccount(username); if (mailServerAccount == null) { printErrorPage(request, response, "No valid mail server account found for user '" + username + "'", null); return; } if (log.isTraceEnabled()) { log.trace("Retrieved MailServerAccount for user '" + username + "'"); } String mailServerProtocol = mailServerAccount.getMailServer().getProtocol(); if (mailServerProtocol == null || "".equals(mailServerProtocol)) { printErrorPage(request, response, "The mail server account protocol is not defined", null); return; } if (log.isTraceEnabled()) { log.trace("Mail server protocol: " + mailServerProtocol); } contentServiceManager.openConnection(mailServerAccount); String mailGUID = contentServiceManager.authorize(username, authToken); if (mailGUID == null || "".equals(mailGUID)) { printErrorPage(request, response, "Email retrieving is not authorized" + " or the email is not present in the Inbox folder anymore.", null); return; } String messageid = Utility.getKeyPart(mailGUID, 2); if (messageid == null || "".equals(messageid)) { printErrorPage(request, response, "Unable to retrieve the message id ", null); return; } if (log.isTraceEnabled()) { log.trace("Message ID: " + messageid); } Message message = contentServiceManager.getMessage(messageid); if (message == null) { printErrorPage(request, response, "The email is not present in " + "the Inbox folder anymore (id " + messageid + ").", null); return; } if (log.isTraceEnabled()) { log.trace("Retrieved mail from mail server with Message ID: " + messageid); } List partsList = MessageParser.getAllPartsOfMessage(message, false); if (partsList == null) { printErrorPage(request, response, "The email doesn't have attachments", null); return; } InternalPart part = getInternalPart(partsList, attachmentIndex); if (part == null) { printErrorPage(request, response, "The email doesn't have attachments" + " with index " + attachmentIndex, null); return; } if (log.isTraceEnabled()) { log.trace("Retrieved part with index: " + attachmentIndex); } if (part == null || part.getDHandler() == null || part.getDHandler().getInputStream() == null) { printErrorPage(request, response, "Error while streaming the attachment.", null); return; } InputStream in = part.getDHandler().getInputStream(); response.setContentType(ContentProviderUtil.createHttpContentType(part)); response.setHeader("Content-Disposition", " filename=\"" + part.getFileName() + "\""); OutputStream out = response.getOutputStream(); IOUtils.copy(in, out); out.flush(); out.close(); in.close(); } catch (Exception ex) { printErrorPage(request, response, ex.toString(), ex); } finally { try { contentServiceManager.closeConnection(); if (log.isTraceEnabled()) { log.trace("Connection closed"); } } catch (ContentProviderException ex) { log.error("Error closing connection ", ex); } if (log.isTraceEnabled()) { log.trace("End handling request."); } // // Since the session is not really useful, we force that a request is // served by a new session and that a session serves just one request. // In such way, we don't have useless sessions. As drawback for every // request a new session is created. // Comparing advantages vs drawbacks, we prefer one session - one request. // session.invalidate(); } }
From source file:com.liferay.portal.action.LoginAction.java
public static void login(HttpServletRequest req, HttpServletResponse res, String login, String password, boolean rememberMe) throws Exception { CookieKeys.validateSupportCookie(req); HttpSession ses = req.getSession(); long userId = GetterUtil.getLong(login); int authResult = Authenticator.FAILURE; Company company = PortalUtil.getCompany(req); ////w w w . j a va 2s. c o m boolean ldaplogin = false; if (PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_ENABLED).equals("true")) { LdapContext ctx = PortalLDAPUtil.getContext(company.getCompanyId()); String accountname = ""; try { User user1 = UserLocalServiceUtil.getUserByScreenName(company.getCompanyId(), login); Properties env = new Properties(); String baseProviderURL = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_BASE_PROVIDER_URL); String userDN = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_USERS_DN); String baseDN = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_BASE_DN); String filter = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_SEARCH_FILTER); filter = StringUtil.replace(filter, new String[] { "@company_id@", "@email_address@", "@screen_name@", "@user_id@" }, new String[] { String.valueOf(company.getCompanyId()), "", login, login }); try { SearchControls cons = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0, null, false, false); NamingEnumeration enu = ctx.search(userDN, filter, cons); if (enu.hasMoreElements()) { SearchResult result = (SearchResult) enu.nextElement(); accountname = result.getName(); } } catch (Exception e1) { e1.printStackTrace(); } env.put(Context.INITIAL_CONTEXT_FACTORY, PrefsPropsUtil.getString(PropsUtil.LDAP_FACTORY_INITIAL)); env.put(Context.PROVIDER_URL, LDAPUtil.getFullProviderURL(baseProviderURL, baseDN)); env.put(Context.SECURITY_PRINCIPAL, accountname + "," + userDN); env.put(Context.SECURITY_CREDENTIALS, password); new InitialLdapContext(env, null); ldaplogin = true; System.out.println("LDAP Login"); } catch (Exception e) { SessionErrors.add(req, "ldapAuthentication"); e.printStackTrace(); System.out.println("LDAP error login"); return; } } // Map headerMap = new HashMap(); Enumeration enu1 = req.getHeaderNames(); while (enu1.hasMoreElements()) { String name = (String) enu1.nextElement(); Enumeration enu2 = req.getHeaders(name); List headers = new ArrayList(); while (enu2.hasMoreElements()) { String value = (String) enu2.nextElement(); headers.add(value); } headerMap.put(name, (String[]) headers.toArray(new String[0])); } Map parameterMap = req.getParameterMap(); if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_EA)) { authResult = UserLocalServiceUtil.authenticateByEmailAddress(company.getCompanyId(), login, password, headerMap, parameterMap); userId = UserLocalServiceUtil.getUserIdByEmailAddress(company.getCompanyId(), login); } else if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_SN)) { authResult = UserLocalServiceUtil.authenticateByScreenName(company.getCompanyId(), login, password, headerMap, parameterMap); userId = UserLocalServiceUtil.getUserIdByScreenName(company.getCompanyId(), login); } else if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_ID)) { authResult = UserLocalServiceUtil.authenticateByUserId(company.getCompanyId(), userId, password, headerMap, parameterMap); } boolean OTPAuth = false; if (GetterUtil.getBoolean(PropsUtil.get("use.yubicoauthentication"), false) == true) { String otppasswd = ParamUtil.getString(req, "otp"); String userslist = GetterUtil.getString(PropsUtil.get("yubico.users.not.require.otp"), "root"); if (userslist.contains(login)) { authResult = Authenticator.SUCCESS; } else { OTPAuth = SecurityUtils.verifyOTP(otppasswd, login); if (authResult == Authenticator.SUCCESS && OTPAuth) { authResult = Authenticator.SUCCESS; } else { authResult = Authenticator.FAILURE; } } } if (PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_ENABLED).equals("true")) { if (!login.equals("root")) { if (ldaplogin) { authResult = Authenticator.SUCCESS; } } } if (authResult == Authenticator.SUCCESS) { boolean loginViaPortal = true; setLoginCookies(req, res, ses, userId, rememberMe); // login to epsos String language = GeneralUtils.getLocale(req); SpiritEhrWsClientInterface webService = EpsosHelperService.getInstance().getWebService(req); InitUserObj initUserObj = EpsosHelperImpl.createEpsosUserInformation(req, res, language, webService, userId, company.getCompanyId(), login, loginViaPortal); SpiritUserClientDto usr = initUserObj.getUsr(); Assertion assertion = initUserObj.getAssertion(); if (Validator.isNotNull(usr)) { req.getSession().setAttribute(EpsosHelperService.EPSOS_LOGIN_INFORMATION_ASSERTIONID, assertion.getID()); req.getSession().setAttribute(EpsosHelperService.EPSOS_LOGIN_INFORMATION_ASSERTION, assertion); req.getSession().setAttribute(EPSOS_LOGIN_INFORMATION_ATTRIBUTE, usr); } else { SessionErrors.add(req, "User doesn't belong to epSOS role so you can't login"); } if (Validator.isNull(usr) && (!(login.equals("root")))) { try { Cookie cookie = new Cookie(CookieKeys.ID, StringPool.BLANK); cookie.setMaxAge(0); cookie.setPath("/"); CookieKeys.addCookie(res, cookie); cookie = new Cookie(CookieKeys.PASSWORD, StringPool.BLANK); cookie.setMaxAge(0); cookie.setPath("/"); CookieKeys.addCookie(res, cookie); try { ses.invalidate(); } catch (Exception e) { } } catch (Exception e) { req.setAttribute(PageContext.EXCEPTION, e); } throw new AuthException(); } } else { throw new AuthException(); } }
From source file:com.sundevils.web.controller.TopController.java
@RequestMapping(value = "**/reqModify", method = { RequestMethod.POST, RequestMethod.GET }) public ModelAndView reqPermissionPage(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException { String role = (String) session.getAttribute("Role"); if (role == null) { ModelAndView model = new ModelAndView(); model.setViewName("index"); return model; } else if (role.equals("USER") || role.equals("MERCHANT")) { ModelAndView model = null;//from w ww . j a v a 2 s . co m try { String updateParameter = ""; String ManagerName = ""; String updateParameterType = ""; int count = 0; model = new ModelAndView(); if (request.getParameter("submit") != null) { updateParameter = request.getParameter("newvalue"); updateParameterType = request.getParameter("searchcat"); if (request.getParameter("newvalue").isEmpty()) { model.addObject("status", "Field is Empty"); model.setViewName("requestpermissionmodify"); } else if ((request.getParameter("searchcat").equals("phonenumber") || request.getParameter("searchcat").equals("zip")) && (!request.getParameter("newvalue").matches("[0-9]+$"))) { model.addObject("status", "Invalid Entry"); model.setViewName("requestpermissionmodify"); } else if ((request.getParameter("searchcat").equals("address") || request.getParameter("searchcat").equals("businesslicense")) && (!request.getParameter("newvalue").matches("[\\p{Alnum}\\p{Punct}]*"))) { model.addObject("status", "Invalid Entry"); model.setViewName("requestpermissionmodify"); } else if (request.getParameter("searchcat").equals("email") && (!request.getParameter("newvalue").matches( "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"))) { model.addObject("status", "Invalid Entry"); model.setViewName("requestpermissionmodify"); } else if ((request.getParameter("searchcat").equals("firstname") || request.getParameter("searchcat").equals("lastname") || request.getParameter("searchcat").equals("state")) && (!request.getParameter("newvalue").matches("[a-zA-Z]+(\\s+[a-zA-Z]+)*"))) { model.addObject("status", "Invalid Entry"); model.setViewName("requestpermissionmodify"); } else { ModifyUsersHandler handler = new ModifyUsersHandler(); ResultSet rs = handler.requestCountHandler(); try { while (rs.next()) { ManagerName = rs.getString("username"); count = rs.getInt("requestcount"); count = count + 1; handler.updateCountHandler(count, ManagerName); break; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } handler.requestModifyHandler((String) request.getSession().getAttribute("USERNAME"), updateParameter, updateParameterType, ManagerName); if (role.equalsIgnoreCase("USER")) { model.addObject("status", "Request Successfully Sent"); model.setViewName("requestpermissionmodify"); } else if (role.equalsIgnoreCase("MERCHANT")) { model.addObject("status", "Request Successfully Sent"); model.setViewName("requestpermissionmodify"); } } } else { ModifyUsersHandler handler = new ModifyUsersHandler(); model.addObject("managers", handler.requestManagers()); model.setViewName("requestpermissionmodify"); } } catch (Exception e) { e.printStackTrace(); } return model; } else { ModelAndView model = new ModelAndView(); LoginHandler handler = new LoginHandler(); String userName = (String) session.getAttribute("USERNAME"); handler.updateLoggedInFlag(userName, 0); session.invalidate(); model.setViewName("index"); return model; } }
From source file:sg.ncl.MainController.java
private void removeSessionVariables(HttpSession session) { log.info("removing session variables: email: {}, userid: {}, user first name: {}", session.getAttribute(webProperties.getSessionEmail()), session.getAttribute(webProperties.getSessionUserId()), session.getAttribute(webProperties.getSessionUserFirstName())); session.removeAttribute(webProperties.getSessionEmail()); session.removeAttribute(webProperties.getSessionUserId()); session.removeAttribute(webProperties.getSessionUserFirstName()); session.removeAttribute(webProperties.getSessionRoles()); session.removeAttribute(webProperties.getSessionJwtToken()); session.invalidate(); }
From source file:com.sundevils.web.controller.TopController.java
@RequestMapping(value = "**/modifyUs", method = { RequestMethod.POST, RequestMethod.GET }) public ModelAndView modifyUsersPage(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException { String role = (String) session.getAttribute("Role"); if (role == null) { ModelAndView model = new ModelAndView(); model.setViewName("index"); return model; } else if (role.equals("EMPLOYEE") || role.equals("MANAGER")) { ModelAndView model = null;//www. java 2 s .c o m try { String searchParameter = ""; String deleteParameter = ""; String accountnumber = ""; String searchParameterType = ""; model = new ModelAndView(); model.setViewName("modifyUsers"); if (request.getParameter("delete") != null) { deleteParameter = request.getParameter("hiddenUser"); accountnumber = request.getParameter("hiddenUserNumber"); ModifyUsersHandler handler = new ModifyUsersHandler(); handler.deleteRequestHandler(deleteParameter, accountnumber); searchParameter = request.getParameter("hiddenUser"); searchParameterType = "UserName"; model.addObject("users", handler.requestHandler(searchParameter, searchParameterType)); model.addObject("title", "All users in the database"); model.addObject("status", "User deleted Successfully"); if (role.equalsIgnoreCase("EMPLOYEE")) { model.setViewName("modifyUsersemployee"); } else if (role.equalsIgnoreCase("MANAGER")) { model.setViewName("modifyUsers"); } } else if (request.getParameter("submit") != null) { if (request.getParameter("username").isEmpty()) { model.addObject("status", "Invalid account"); model.setViewName("modifyUsers"); } else { searchParameter = request.getParameter("username"); searchParameterType = request.getParameter("searchcat"); ModifyUsersHandler handler = new ModifyUsersHandler(); ArrayList<ModifyUser> test = (ArrayList<ModifyUser>) handler.requestHandler(searchParameter, searchParameterType); if (test.size() != 0) model.addObject("users", test); else model.addObject("status", "No user present who satisifies the criteria"); model.addObject("title", "All users in the database"); model.addObject("message", "This is protected page!"); if (role.equalsIgnoreCase("EMPLOYEE")) { model.setViewName("modifyUsersemployee"); } else if (role.equalsIgnoreCase("MANAGER")) { model.setViewName("modifyUsers"); } } } else if (role.equalsIgnoreCase("EMPLOYEE")) { model.setViewName("modifyUsersemployee"); } else if (role.equalsIgnoreCase("MANAGER")) { model.setViewName("modifyUsers"); } else if ((request.getParameter("searchcat").equals("AccountNumber") || request.getParameter("searchcat").equals("UserName")) && (!request.getParameter("username").matches("[0-9 ]+"))) { model.addObject("status", "Invalid Entry"); if (role.equalsIgnoreCase("EMPLOYEE")) { model.setViewName("modifyUsersemployee"); } else if (role.equalsIgnoreCase("MANAGER")) { model.setViewName("modifyUsers"); } } else if (request.getParameter("searchcat").equals("Name") && (!request.getParameter("username").matches("[a-zA-Z]+(\\s+[a-zA-Z]+)*"))) { model.addObject("status", "Invalid Entry"); if (role.equalsIgnoreCase("EMPLOYEE")) { model.setViewName("modifyUsersemployee"); } else if (role.equalsIgnoreCase("MANAGER")) { model.setViewName("modifyUsers"); } } } catch (Exception e) { e.printStackTrace(); } return model; } else { ModelAndView model = new ModelAndView(); LoginHandler handler = new LoginHandler(); String userName = (String) session.getAttribute("USERNAME"); handler.updateLoggedInFlag(userName, 0); session.invalidate(); model.setViewName("index"); return model; } }
From source file:onl.netfishers.netshot.RestService.java
/** * Logout./*from www .j av a 2 s .c om*/ * * @param request the request * @return the boolean * @throws WebApplicationException the web application exception */ @DELETE @Path("user/{id}") @RolesAllowed("readonly") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public void logout(@Context HttpServletRequest request) throws WebApplicationException { logger.debug("REST logout request."); HttpSession httpSession = request.getSession(); httpSession.invalidate(); }
From source file:onl.netfishers.netshot.RestService.java
/** * Login./*from w w w .ja v a 2 s . c om*/ * * @param request the request * @param rsLogin the rs login * @return the user * @throws WebApplicationException the web application exception */ @POST @PermitAll @Path("user") @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public User login(@Context HttpServletRequest request, RsLogin rsLogin) throws WebApplicationException { logger.debug("REST authentication request, username {}.", rsLogin.getUsername()); User user = null; Session session = Database.getSession(); try { user = (User) session.bySimpleNaturalId(User.class).load(rsLogin.getUsername()); } catch (HibernateException e) { logger.error("Unable to retrieve the user {}.", rsLogin.getUsername(), e); throw new NetshotBadRequestException("Unable to retrieve the user.", NetshotBadRequestException.NETSHOT_DATABASE_ACCESS_ERROR); } finally { session.close(); } if (user != null && user.isLocal()) { if (!user.checkPassword(rsLogin.getPassword())) { user = null; } } else { User remoteUser = Radius.authenticate(rsLogin.getUsername(), rsLogin.getPassword()); if (remoteUser != null && user != null) { remoteUser.setLevel(user.getLevel()); } user = remoteUser; } if (user == null) { HttpSession httpSession = request.getSession(); httpSession.invalidate(); } else { HttpSession httpSession = request.getSession(); httpSession.setAttribute("user", user); httpSession.setMaxInactiveInterval(User.MAX_IDLE_TIME); return user; } throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build()); }
From source file:com.sundevils.web.controller.TopController.java
@RequestMapping(value = "/approvetransaction", method = { RequestMethod.POST, RequestMethod.GET }) public ModelAndView approveTransaction(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException, SQLException { String role = ""; String requestType = ""; String[] authRequests = null; role = (String) session.getAttribute("Role"); double balance = 0.0; boolean destinationFlag = true; boolean sourceFlag = true; double destinationAmount = 0.0; String destinationAccountNumber = ""; double sourceAmount = 0.0; String sourceAccountNumber = ""; Boolean status = false;/* w w w. ja v a 2s. c o m*/ if (role == null) { ModelAndView model = new ModelAndView(); model.setViewName("index"); return model; } else if (role.equals("EMPLOYEE")) { ModelAndView model = new ModelAndView(); model.setViewName("approve"); List<TransactionDetails> transDetails = new ArrayList<TransactionDetails>(); RequestAuthorize authorize = new RequestAuthorize(); if (request.getParameter("submit") != null) { authRequests = request.getParameterValues("check"); requestType = request.getParameter("Type"); if (authRequests != null) { balance = authorize.getBalance(authRequests); if (requestType.equals("Approve")) { if (authRequests.length > 1) destinationFlag = authorize.checkSameDestination(authRequests); if (destinationFlag) { destinationAccountNumber = authorize.getDestinationAccount(authRequests[0]); status = authorize.checkAccountNumber(destinationAccountNumber); if (status) { destinationAmount = authorize.getDestinationBalance(destinationAccountNumber); authorize.approveTransaction(requestType, balance + destinationAmount, authRequests); model.addObject("success", "The approval of normal transaction/s is successfully done"); } else { model.addObject("destinationerror", "Destination account does not exist. Please delete the transaction"); } } else { model.addObject("duplicateaccount", "Transactions belonging to the same destination account should be done at a time while approving."); } } else { if (authRequests.length > 1) sourceFlag = authorize.checkSameSource(authRequests); if (sourceFlag) { sourceAccountNumber = authorize.getSourceAccount(authRequests[0]); status = authorize.checkAccountNumber(sourceAccountNumber); if (status) { sourceAmount = authorize.getSourceBalance(sourceAccountNumber); authorize.rejectTransaction(requestType, balance + sourceAmount, authRequests); model.addObject("success", "The rejection of normal transaction/s is successfully done"); } else { model.addObject("destinationerror", "Destination account does not exist. Please delete the transaction"); } } else { model.addObject("duplicatesourceaccount", "Transactions belonging to the same source account should be done at a time while rejecting."); } } } else { model.addObject("check", "Please check atleast one checkbox to continue"); } } ResultSet rs = authorize.getModDelHandler("pendingapproval", "PAYMENT", 10000); try { while (rs.next()) { TransactionDetails view = new TransactionDetails(); view.setUserName(rs.getString("username")); view.setTransactionId(rs.getString("transactionid")); view.setTransactionAmount(rs.getString("transactionamount")); view.setNewAmount(rs.getString("newamount")); view.setSourceAccount(rs.getString("sourceaccountnumber")); view.setDestAccount(rs.getString("destinationaccountnumber")); view.setDateandTime(rs.getString("dateandtime")); view.setTransferType(rs.getString("transfertype")); view.setStatus(rs.getString("status")); transDetails.add(view); } model.addObject("transactionApprove", transDetails); } catch (SQLException e) { e.printStackTrace(); } return model; } else { ModelAndView model = new ModelAndView(); LoginHandler handler = new LoginHandler(); String userName = (String) session.getAttribute("USERNAME"); handler.updateLoggedInFlag(userName, 0); session.invalidate(); model.setViewName("index"); return model; } }
From source file:com.sundevils.web.controller.TopController.java
@RequestMapping(value = "/criticaltransaction", method = { RequestMethod.POST, RequestMethod.GET }) public ModelAndView criticalTransaction(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException, SQLException { String role = ""; String requestType = ""; String[] authRequests = null; role = (String) session.getAttribute("Role"); double balance = 0.0; boolean destinationFlag = true; boolean sourceFlag = true; double destinationAmount = 0.0; String destinationAccountNumber = ""; double sourceAmount = 0.0; String sourceAccountNumber = ""; Boolean status = false;/* www .j a va 2s . co m*/ if (role == null) { ModelAndView model = new ModelAndView(); model.setViewName("index"); return model; } else if (role.equals("MANAGER")) { ModelAndView model = new ModelAndView(); model.setViewName("critical"); List<TransactionDetails> transDetails = new ArrayList<TransactionDetails>(); RequestAuthorize authorize = new RequestAuthorize(); if (request.getParameter("submit") != null) { authRequests = request.getParameterValues("check"); requestType = request.getParameter("Type"); if (authRequests != null) { balance = authorize.getBalance(authRequests); if (requestType.equals("Approve")) { if (authRequests.length > 1) destinationFlag = authorize.checkSameDestination(authRequests); if (destinationFlag) { destinationAccountNumber = authorize.getDestinationAccount(authRequests[0]); status = authorize.checkAccountNumber(destinationAccountNumber); if (status) { destinationAmount = authorize.getDestinationBalance(destinationAccountNumber); authorize.approveTransaction(requestType, balance + destinationAmount, authRequests); model.addObject("success", "The approval of critical transaction/s is successfully done"); } else { model.addObject("destinationerror", "Destination account does not exist. Please delete the transaction"); } } else { model.addObject("duplicateaccount", "Transactions belonging to the same destination account should be done at a time while approving."); } } else { if (authRequests.length > 1) sourceFlag = authorize.checkSameSource(authRequests); if (sourceFlag) { sourceAccountNumber = authorize.getSourceAccount(authRequests[0]); status = authorize.checkAccountNumber(sourceAccountNumber); if (status) { sourceAmount = authorize.getSourceBalance(sourceAccountNumber); authorize.rejectTransaction(requestType, balance + sourceAmount, authRequests); model.addObject("success", "The rejection of critical transaction/s is successfully done"); } else { model.addObject("destinationerror", "Destination account does not exist. Please delete the transaction"); } } else { model.addObject("duplicatesourceaccount", "Transactions belonging to the same source account should be done at a time while rejecting."); } } } else { model.addObject("check", "Please check atleast one checkbox to continue"); } } ResultSet rs = authorize.getTransactionHandler("pendingapproval", 10000, "PAYMENT"); try { while (rs.next()) { TransactionDetails view = new TransactionDetails(); view.setUserName(rs.getString("username")); view.setTransactionId(rs.getString("transactionid")); view.setTransactionAmount(rs.getString("transactionamount")); view.setNewAmount(rs.getString("newamount")); view.setSourceAccount(rs.getString("sourceaccountnumber")); view.setDestAccount(rs.getString("destinationaccountnumber")); view.setDateandTime(rs.getString("dateandtime")); view.setTransferType(rs.getString("transfertype")); view.setStatus(rs.getString("status")); transDetails.add(view); } model.addObject("transactionApprove", transDetails); } catch (SQLException e) { e.printStackTrace(); } return model; } else { ModelAndView model = new ModelAndView(); LoginHandler handler = new LoginHandler(); String userName = (String) session.getAttribute("USERNAME"); handler.updateLoggedInFlag(userName, 0); session.invalidate(); model.setViewName("index"); return model; } }