From 0211660397bdaaa10007be406d734b13f0b99599 Mon Sep 17 00:00:00 2001 From: Earle Nietzel Date: Wed, 21 Aug 2024 18:25:42 -0400 Subject: [PATCH 1/2] SAK-50402 Portal publish now button visible if user has permission to publish the site https://sakaiproject.atlassian.net/browse/SAK-50402 --- portal/portal-impl/impl/pom.xml | 44 +- .../portal/charon/handlers/SiteHandler.java | 510 ++++++++---------- .../charon/PortalTestConfiguration.java | 99 ++++ .../charon/handlers/SiteHandlerTest.java | 68 ++- .../charon/site/PortalSiteHelperTest.java | 15 - .../morpheus/snippets/siteStatus-snippet.vm | 2 + .../portal/service/PortalServiceImpl.java | 216 +++----- 7 files changed, 479 insertions(+), 475 deletions(-) create mode 100644 portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/PortalTestConfiguration.java delete mode 100644 portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/site/PortalSiteHelperTest.java diff --git a/portal/portal-impl/impl/pom.xml b/portal/portal-impl/impl/pom.xml index 6aa59600235e..e592c336e380 100644 --- a/portal/portal-impl/impl/pom.xml +++ b/portal/portal-impl/impl/pom.xml @@ -75,6 +75,10 @@ org.springframework spring-tx + + org.springframework + spring-context + org.sakaiproject.pasystem pasystem-api @@ -87,7 +91,6 @@ org.apache.commons commons-lang3 - org.apache.commons commons-collections4 @@ -100,11 +103,6 @@ javax.servlet javax.servlet-api - - jtidy - jtidy - test - org.apache.velocity velocity @@ -128,21 +126,6 @@ com.fasterxml.jackson.core jackson-databind - - org.mockito - mockito-core - test - - - org.powermock - powermock-api-mockito2 - test - - - org.powermock - powermock-module-junit4 - test - org.apache.commons commons-text @@ -155,9 +138,20 @@ org.jsoup jsoup + + org.springframework + spring-test + + + org.mockito + mockito-inline + 3.7.0 + test + + src/java ${basedir}/src/bundle @@ -176,14 +170,8 @@ src/test/java - ${basedir}/src/test/resources - - **/*.* - - false + src/test/resources - - src/java diff --git a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/SiteHandler.java b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/SiteHandler.java index b431c640d505..fd921abffa0a 100644 --- a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/SiteHandler.java +++ b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/SiteHandler.java @@ -25,16 +25,15 @@ import java.text.DateFormat; import java.time.Instant; import java.util.ArrayList; -import java.util.Arrays; import java.util.Date; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; +import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -42,14 +41,14 @@ import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import org.sakaiproject.authz.api.Role; -import org.sakaiproject.authz.cover.SecurityService; -import org.sakaiproject.component.cover.ComponentManager; -import org.sakaiproject.component.cover.ServerConfigurationService; +import org.sakaiproject.authz.api.SecurityService; +import org.sakaiproject.component.api.ServerConfigurationService; +import org.sakaiproject.coursemanagement.api.CourseManagementService; import org.sakaiproject.coursemanagement.api.exception.IdNotFoundException; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.api.ResourcePropertiesEdit; import org.sakaiproject.event.api.Event; -import org.sakaiproject.event.cover.EventTrackingService; +import org.sakaiproject.event.api.EventTrackingService; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.portal.api.Portal; @@ -68,29 +67,30 @@ import org.sakaiproject.presence.api.PresenceService; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SitePage; +import org.sakaiproject.site.api.SiteService; import org.sakaiproject.site.api.ToolConfiguration; -import org.sakaiproject.site.cover.SiteService; -import org.sakaiproject.thread_local.cover.ThreadLocalManager; +import org.sakaiproject.thread_local.api.ThreadLocalManager; import org.sakaiproject.time.api.UserTimeService; import org.sakaiproject.tool.api.ActiveTool; +import org.sakaiproject.tool.api.ActiveToolManager; import org.sakaiproject.tool.api.Session; +import org.sakaiproject.tool.api.SessionManager; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.tool.api.ToolException; -import org.sakaiproject.tool.api.ToolManager; import org.sakaiproject.tool.api.ToolSession; -import org.sakaiproject.tool.cover.ActiveToolManager; -import org.sakaiproject.tool.cover.SessionManager; import org.sakaiproject.user.api.Preferences; import org.sakaiproject.user.api.PreferencesEdit; +import org.sakaiproject.user.api.PreferencesService; +import org.sakaiproject.user.api.UserDirectoryService; import org.sakaiproject.user.api.UserNotDefinedException; -import org.sakaiproject.user.cover.PreferencesService; -import org.sakaiproject.user.cover.UserDirectoryService; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.Validator; import org.sakaiproject.util.Web; import org.sakaiproject.util.RequestFilter; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; /** @@ -99,27 +99,13 @@ * @version $Rev$ */ @Slf4j -public class SiteHandler extends WorksiteHandler -{ - +public class SiteHandler extends WorksiteHandler { private static final String INCLUDE_SITE_NAV = "include-site-nav"; - private static final String INCLUDE_LOGO = "include-logo"; - private static final String INCLUDE_TABS = "include-tabs"; - // Cannot be static to allow for this class to be extended at a different fragment - protected String URL_FRAGMENT = "site"; - - private static ResourceLoader rb = new ResourceLoader("sitenav"); - - // When these strings appear in the URL they will be replaced by a calculated value based on the context. - // This can be replaced by the users myworkspace. - private String mutableSitename ="-"; - // This can be replaced by the page on which a tool appears. - private String mutablePagename ="-"; + private static final ResourceLoader rb = new ResourceLoader("sitenav"); - // SAK-29180 - Normalize the properties, keeping the legacy pda sakai.properties names through Sakai-11 at least private static final String BYPASS_URL_PROP = "portal.bypass"; private static final String LEGACY_BYPASS_URL_PROP = "portal.pda.bypass"; private static final String DEFAULT_BYPASS_URL = "\\.jpg$|\\.gif$|\\.js$|\\.png$|\\.jpeg$|\\.prf$|\\.css$|\\.zip$|\\.pdf\\.mov$|\\.json$|\\.jsonp$\\.xml$|\\.ajax$|\\.xls$|\\.xlsx$|\\.doc$|\\.docx$|uvbview$|linktracker$|hideshowcolumns$|scormplayerpage$|scormcompletionpage$"; @@ -149,24 +135,39 @@ public class SiteHandler extends WorksiteHandler private static final String SAK_PROP_SHOW_SITE_LABELS = "portal.siteList.siteLabels"; private static final boolean SAK_PROP_SHOW_SITE_LABELS_DFLT = true; - private static final long AUTO_FAVORITES_REFRESH_INTERVAL_MS = 30000; + @Autowired private CourseManagementService courseManagementService; + @Autowired private ActiveToolManager toolManager; + @Autowired private EventTrackingService eventTrackingService; + @Autowired private PreferencesService preferencesService; + @Autowired private PresenceService presenceService; + @Autowired private ProfileImageLogic profileImageLogic; + @Autowired private SecurityService securityService; + @Autowired private ServerConfigurationService serverConfigurationService; + @Autowired private SessionManager sessionManager; + @Autowired private SiteService siteService; + @Autowired private ThreadLocalManager threadLocalManager; + @Autowired private UserDirectoryService userDirectoryService; + @Resource(name = "org.sakaiproject.time.api.UserTimeService") + private UserTimeService userTimeService; - protected ProfileImageLogic imageLogic; - private org.sakaiproject.coursemanagement.api.CourseManagementService cms = (org.sakaiproject.coursemanagement.api.CourseManagementService) ComponentManager.get(org.sakaiproject.coursemanagement.api.CourseManagementService.class); + // When these strings appear in the URL they will be replaced by a calculated value based on the context. + // This can be replaced by the users myworkspace. + private final String mutableSitename; + // This can be replaced by the page on which a tool appears. + private final String mutablePagename; - private UserTimeService userTimeService; + // Cannot be static to allow for this class to be extended at a different fragment + protected String URL_FRAGMENT = "site"; + + public SiteHandler() { + SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); + + mutableSitename = serverConfigurationService.getString("portal.mutable.sitename", "-"); + mutablePagename = serverConfigurationService.getString("portal.mutable.pagename", "-"); - public SiteHandler() - { - // Allow any sub-classes to register their own URL_FRAGMENT - // https://stackoverflow.com/questions/41566202/possible-to-avoid-default-call-to-super-in-java if(this.getClass() == SiteHandler.class) { setUrlFragment(URL_FRAGMENT); } - mutableSitename = ServerConfigurationService.getString("portal.mutable.sitename", "-"); - mutablePagename = ServerConfigurationService.getString("portal.mutable.pagename", "-"); - imageLogic = ComponentManager.get(ProfileImageLogic.class); - userTimeService = ComponentManager.get(UserTimeService.class); } @Override @@ -221,7 +222,6 @@ public int doGet(String[] parts, HttpServletRequest req, HttpServletResponse res // 0 1 2 3 4 if ((siteId != null) && (parts.length == 5) && (parts[3].equals("tool-reset"))) { - toolId = parts[4]; String toolUrl = req.getContextPath() + "/site/" + siteId + "/tool" + Web.makePath(parts, 4, parts.length); portalService.setResetState("true"); @@ -237,7 +237,7 @@ public int doGet(String[] parts, HttpServletRequest req, HttpServletResponse res if ((siteId != null) && (parts.length == 5) && (parts[3].equals("page-reset"))) { pageId = parts[4]; - Site site = null; + Site site; try { // This should understand aliases as well as IDs @@ -254,14 +254,12 @@ public int doGet(String[] parts, HttpServletRequest req, HttpServletResponse res boolean hasJSR168 = false; if (page != null) { - Session s = SessionManager.getCurrentSession(); - Iterator toolz = page.getTools().iterator(); - while(toolz.hasNext()){ - ToolConfiguration pageTool = toolz.next(); - ToolSession ts = s.getToolSession(pageTool.getId()); - ts.clearAttributes(); - if ( portal.isPortletPlacement(pageTool) ) hasJSR168 = true; - } + Session s = sessionManager.getCurrentSession(); + for (ToolConfiguration tool : page.getTools()) { + ToolSession ts = s.getToolSession(tool.getId()); + ts.clearAttributes(); + if (portal.isPortletPlacement(tool)) hasJSR168 = true; + } } String pageUrl = URLUtils.sanitisePath(req.getContextPath() + "/site/" + siteId + "/page" @@ -306,18 +304,18 @@ public void doSite(HttpServletRequest req, HttpServletResponse res, Session sess siteId = portal.getSiteHelper().getGatewaySiteId(); if (siteId == null) { - siteId = ServerConfigurationService.getGatewaySiteId(); + siteId = serverConfigurationService.getGatewaySiteId(); } } else { // TODO Should maybe switch to portal.getSiteHelper().getMyWorkspace() - AllSitesViewImpl allSites = (AllSitesViewImpl) portal.getSiteHelper().getSitesView(SiteView.View.ALL_SITES_VIEW, req, session, siteId); + AllSitesViewImpl allSites = (AllSitesViewImpl) portal.getSiteHelper().getSitesView(SiteView.View.ALL_SITES_VIEW, req, session, null); List sites = (List) allSites.getRenderContextObject(); - if (sites.size() > 0) { + if (!sites.isEmpty()) { siteId = (String) sites.get(0).get("siteId"); } else { - siteId = SiteService.getUserSiteId(userId); + siteId = siteService.getUserSiteId(userId); } } } @@ -329,30 +327,25 @@ public void doSite(HttpServletRequest req, HttpServletResponse res, Session sess // check for a mutable site to be resolved here if (mutableSitename.equalsIgnoreCase(siteId) && (session.getUserId() != null)) { - siteId = SiteService.getUserSiteId(userId); + siteId = siteService.getUserSiteId(userId); } // find the site, for visiting boolean siteDenied = false; Site site = null; - try - { + try { // This should understand aliases as well as IDs site = portal.getSiteHelper().getSiteVisit(siteId); - + // SAK-20509 remap the siteId from the Site object we now have, since it may have originally been an alias, but has since been translated. siteId = site.getId(); - - } - catch (IdUnusedException e) - { - } - catch (PermissionException e) - { - if (ServerConfigurationService.getBoolean("portal.redirectJoin", true) && - userId != null && portal.getSiteHelper().isJoinable(siteId, userId)) - { - String redirectUrl = Web.returnUrl(req, "/join/"+siteId); + + } catch (IdUnusedException e) { + log.debug("Site [{}] not found", siteId); + } catch (PermissionException e) { + if (serverConfigurationService.getBoolean("portal.redirectJoin", true) && + userId != null && portal.getSiteHelper().isJoinable(siteId, userId)) { + String redirectUrl = Web.returnUrl(req, "/join/" + siteId); res.addHeader("Cache-Control", "no-cache"); res.sendRedirect(redirectUrl); return; @@ -380,8 +373,8 @@ public void doSite(HttpServletRequest req, HttpServletResponse res, Session sess // It is also helpful for event log analysis for user trouble or bad behavior. if (siteDenied) { - Event event = EventTrackingService.newEvent(SiteService.EVENT_SITE_VISIT_DENIED, siteId, false); - EventTrackingService.post(event); + Event event = eventTrackingService.newEvent(SiteService.EVENT_SITE_VISIT_DENIED, siteId, false); + eventTrackingService.post(event); } portal.doError(req, res, session, Portal.ERROR_SITE); } @@ -389,7 +382,7 @@ public void doSite(HttpServletRequest req, HttpServletResponse res, Session sess } // Supports urls like: /portal/site/{SITEID}/sakai.announcements - if (site != null && commonToolId != null) + if (commonToolId != null) { ToolConfiguration tc = null; if(!commonToolId.startsWith("sakai.")) @@ -410,8 +403,8 @@ public void doSite(HttpServletRequest req, HttpServletResponse res, Session sess } // Find the pageId looking backwards through the toolId - if (site != null && pageId == null && toolId != null ) { - SitePage p = (SitePage) ToolUtils.getPageForTool(site, toolId); + if (pageId == null && toolId != null) { + SitePage p = ToolUtils.getPageForTool(site, toolId); if ( p != null ) pageId = p.getId(); } @@ -431,8 +424,8 @@ public void doSite(HttpServletRequest req, HttpServletResponse res, Session sess session.removeAttribute(Portal.ATTR_SITE_PAGE + siteId); // SAK-29138 - form a context sensitive title - List providers = PortalSiteHelperImpl.getProviderIDsForSites(((List) Arrays.asList(new Site[] { site }))).get(site.getReference()); - String title = ServerConfigurationService.getString("ui.service","Sakai") + " : " + List providers = PortalSiteHelperImpl.getProviderIDsForSites(List.of(site)).get(site.getReference()); + String title = serverConfigurationService.getString("ui.service","Sakai") + " : " + portal.getSiteHelper().getUserSpecificSiteTitle(site, false, false, providers); // Lookup the page in the site - enforcing access control @@ -443,7 +436,7 @@ public void doSite(HttpServletRequest req, HttpServletResponse res, Session sess } // Check for incomplete URLs in the case of inlined tools - boolean trinity = ServerConfigurationService.getBoolean(ToolUtils.PORTAL_INLINE_EXPERIMENTAL, ToolUtils.PORTAL_INLINE_EXPERIMENTAL_DEFAULT); + boolean trinity = serverConfigurationService.getBoolean(ToolUtils.PORTAL_INLINE_EXPERIMENTAL, ToolUtils.PORTAL_INLINE_EXPERIMENTAL_DEFAULT); if (trinity && toolId == null) { String pagerefUrl = ToolUtils.getPageUrl(req, site, page, getUrlFragment(), false, null, null); @@ -452,7 +445,7 @@ public void doSite(HttpServletRequest req, HttpServletResponse res, Session sess if ( pieces.length > 6 && "tool".equals(pieces[6]) ) { String queryString = req.getQueryString(); if ( queryString != null ) pagerefUrl = URLUtils.sanitisePath(pagerefUrl) + '?' + queryString; - log.debug("Redirecting tool inline url: "+pagerefUrl); + log.debug("Redirecting tool inline url: {}", pagerefUrl); res.addHeader("Cache-Control", "no-cache"); res.sendRedirect(pagerefUrl); return; @@ -468,13 +461,13 @@ public void doSite(HttpServletRequest req, HttpServletResponse res, Session sess ToolConfiguration siteTool = null; if ( toolId != null ) { - siteTool = SiteService.findTool(toolId); + siteTool = siteService.findTool(toolId); if ( siteTool != null && parts.length >= 5 ) { commonToolId = siteTool.getToolId(); // Does the tool allow us to buffer? - allowBuffer = allowBufferContent(req, site, siteTool); - log.debug("allowBuffer="+allowBuffer+" url="+req.getRequestURL()); + allowBuffer = allowBufferContent(site, siteTool); + log.debug("allowBuffer={} url={}", allowBuffer, req.getRequestURL()); if ( allowBuffer ) { TCP = req.getContextPath() + req.getServletPath() + Web.makePath(parts, 1, 5); @@ -485,14 +478,14 @@ public void doSite(HttpServletRequest req, HttpServletResponse res, Session sess if ( matched ) { log.debug("Bypassing buffer to forwardTool per configuration"); - ActiveTool tool = ActiveToolManager.getActiveTool(commonToolId); + ActiveTool tool = toolManager.getActiveTool(commonToolId); portal.forwardTool(tool, req, res, siteTool, siteTool.getSkin(), TCP, toolPathInfo); return; } // Inform calls to includeTool() that the default is // this thread is inlining a tool. - ThreadLocalManager.set("sakai:inline-tool","true"); + threadLocalManager.set("sakai:inline-tool","true"); } } } @@ -505,8 +498,8 @@ public void doSite(HttpServletRequest req, HttpServletResponse res, Session sess .getSkin(), req, site); if (userId != null) { - final Preferences readOnlyPrefs = PreferencesService.getPreferences(userId); - final ResourceProperties siteNavProps = readOnlyPrefs.getProperties(org.sakaiproject.user.api.PreferencesService.SITENAV_PREFS_KEY); + final Preferences readOnlyPrefs = preferencesService.getPreferences(userId); + final ResourceProperties siteNavProps = readOnlyPrefs.getProperties(PreferencesService.SITENAV_PREFS_KEY); final String currentExpanded = siteNavProps.getProperty(PortalConstants.PROP_CURRENT_EXPANDED); final String expandedSite = siteNavProps.getProperty(PortalConstants.PROP_EXPANDED_SITE); @@ -514,20 +507,20 @@ public void doSite(HttpServletRequest req, HttpServletResponse res, Session sess if (!StringUtils.equals(currentExpanded, "true") || !StringUtils.equals(expandedSite, siteId)) { PreferencesEdit prefs = null; try { - prefs = PreferencesService.edit(userId); - ResourcePropertiesEdit props = prefs.getPropertiesEdit(org.sakaiproject.user.api.PreferencesService.SITENAV_PREFS_KEY); + prefs = preferencesService.edit(userId); + ResourcePropertiesEdit props = prefs.getPropertiesEdit(PreferencesService.SITENAV_PREFS_KEY); props.addProperty(PortalConstants.PROP_CURRENT_EXPANDED, "true"); props.addProperty(PortalConstants.PROP_EXPANDED_SITE, siteId); - boolean themeEnabled = ServerConfigurationService.getBoolean(PortalConstants.PROP_PORTAL_THEMES, true); + boolean themeEnabled = serverConfigurationService.getBoolean(PortalConstants.PROP_PORTAL_THEMES, true); if (!themeEnabled) { - prefs.getPropertiesEdit(org.sakaiproject.user.api.PreferencesService.USER_SELECTED_UI_THEME_PREFS).addProperty("theme", "sakaiUserTheme-notSet"); + prefs.getPropertiesEdit(PreferencesService.USER_SELECTED_UI_THEME_PREFS).addProperty("theme", "sakaiUserTheme-notSet"); } } catch (Exception any) { log.warn("Exception caught whilst setting expanded navigation or theme properties: {}", any.toString()); - if (prefs != null) PreferencesService.cancel(prefs); + if (prefs != null) preferencesService.cancel(prefs); } finally { - if (prefs != null) PreferencesService.commit(prefs); + if (prefs != null) preferencesService.commit(prefs); } } } @@ -565,23 +558,23 @@ public void doSite(HttpServletRequest req, HttpServletResponse res, Session sess StringBuffer queryUrl = req.getRequestURL(); String queryString = req.getQueryString(); if ( queryString != null ) queryUrl.append('?').append(queryString); - log.debug("It is tacky to return markup on a POST CTI="+commonToolId+" URL="+queryUrl); + log.debug("It is tacky to return markup on a POST CTI={} URL={}", commonToolId, queryUrl); } log.debug("BufferedResponse success"); rcontext.put("bufferedResponse", Boolean.TRUE); Map bufferMap = (Map) BC; - rcontext.put("responseHead", (String) bufferMap.get("responseHead")); - rcontext.put("responseBody", (String) bufferMap.get("responseBody")); + rcontext.put("responseHead", bufferMap.get("responseHead")); + rcontext.put("responseBody", bufferMap.get("responseBody")); } rcontext.put("siteId", siteId); - boolean showShortDescription = Boolean.valueOf(ServerConfigurationService.getBoolean("portal.title.shortdescription.show", false)); + boolean showShortDescription = serverConfigurationService.getBoolean("portal.title.shortdescription.show", false); if (showShortDescription) { rcontext.put("shortDescription", Web.escapeHtml(site.getShortDescription())); } - if (SiteService.isUserSite(siteId)){ + if (siteService.isUserSite(siteId)){ rcontext.put("siteTitle", rb.getString("sit_mywor") ); rcontext.put("siteUrl", site.getUrl()); rcontext.put("siteTitleTruncated", rb.getString("sit_mywor") ); @@ -593,12 +586,12 @@ public void doSite(HttpServletRequest req, HttpServletResponse res, Session sess rcontext.put("isUserSite", false); } - rcontext.put("showFavStarsInSitesBar",ServerConfigurationService.getBoolean(SAK_PROP_SHOW_FAV_STARS, SAK_PROP_SHOW_FAV_STARS_DFLT)); - rcontext.put("showFavStarsOnAllFavSites",ServerConfigurationService.getBoolean(SAK_PROP_SHOW_FAV_STARS_ON_ALL, SAK_PROP_SHOW_FAV_STARS_ON_ALL_DFLT)); + rcontext.put("showFavStarsInSitesBar", serverConfigurationService.getBoolean(SAK_PROP_SHOW_FAV_STARS, SAK_PROP_SHOW_FAV_STARS_DFLT)); + rcontext.put("showFavStarsOnAllFavSites", serverConfigurationService.getBoolean(SAK_PROP_SHOW_FAV_STARS_ON_ALL, SAK_PROP_SHOW_FAV_STARS_ON_ALL_DFLT)); - rcontext.put("showSiteLabels",ServerConfigurationService.getBoolean(SAK_PROP_SHOW_SITE_LABELS, SAK_PROP_SHOW_SITE_LABELS_DFLT)); - - rcontext.put("activePageId", page.getId()); + rcontext.put("showSiteLabels", serverConfigurationService.getBoolean(SAK_PROP_SHOW_SITE_LABELS, SAK_PROP_SHOW_SITE_LABELS_DFLT)); + + rcontext.put("activePageId", page != null ? page.getId() : null); addLocale(rcontext, site, session.getUserId()); @@ -611,23 +604,19 @@ public void doSite(HttpServletRequest req, HttpServletResponse res, Session sess portal.includeBottom(rcontext, site); - //Log the visit into SAKAI_EVENT - begin - try{ - boolean presenceEvents = ServerConfigurationService.getBoolean("presence.events.log", true); - if (presenceEvents) - org.sakaiproject.presence.cover.PresenceService.setPresence(siteId + PresenceService.PRESENCE_SUFFIX); - }catch(Exception e){} - //End - log the visit into SAKAI_EVENT + boolean presenceEvents = serverConfigurationService.getBoolean("presence.events.log", true); + if (presenceEvents) presenceService.setPresence(siteId + PresenceService.PRESENCE_SUFFIX); rcontext.put("currentUrlPath", RequestFilter.serverUrl(req) + req.getContextPath() + URLUtils.getSafePathInfo(req)); - rcontext.put("usePortalSearch", ServerConfigurationService.getBoolean("portal.search.enabled", true) - && ServerConfigurationService.getBoolean("search.enable", false)); - rcontext.put("portalSearchPageSize", ServerConfigurationService.getString("portal.search.pageSize", "10")); + rcontext.put("usePortalSearch", serverConfigurationService.getBoolean("portal.search.enabled", true) + && serverConfigurationService.getBoolean("search.enable", false)); + rcontext.put("portalSearchPageSize", serverConfigurationService.getString("portal.search.pageSize", "10")); + rcontext.put("publishSiteButton", siteService.allowUpdateSite(siteId)); //Show a confirm dialog when publishing an unpublished site. - rcontext.put("publishSiteDialogEnabled", ServerConfigurationService.getBoolean("portal.publish.site.confirm.enabled", false)); + rcontext.put("publishSiteDialogEnabled", serverConfigurationService.getBoolean("portal.publish.site.confirm.enabled", false)); Map toolTitles = new HashMap<>(); site.getPages().forEach(pageNow -> { @@ -652,9 +641,9 @@ public void doSite(HttpServletRequest req, HttpServletResponse res, Session sess } } else if (StringUtils.equals(site.getProperties().getProperty("publish_type"), "auto")) { // automatically-managed publishing try { - if (cms.getAcademicSession(site.getProperties().getProperty("term_eid")).getStartDate() != null) { - long leadtime = ServerConfigurationService.getInt("course_site_publish_service.num_days_before_term_starts", 0) * 1000L * 60L * 60L * 24L; - Date publishDate = new Date(cms.getAcademicSession(site.getProperties().getProperty("term_eid")).getStartDate().getTime() - leadtime); + if (courseManagementService.getAcademicSession(site.getProperties().getProperty("term_eid")).getStartDate() != null) { + long leadtime = serverConfigurationService.getInt("course_site_publish_service.num_days_before_term_starts", 0) * 1000L * 60L * 60L * 24L; + Date publishDate = new Date(courseManagementService.getAcademicSession(site.getProperties().getProperty("term_eid")).getStartDate().getTime() - leadtime); if (publishDate.toInstant().isAfter(Instant.now())) { rcontext.put("scheduledate", userTimeService.dateFormat(publishDate, rb.getLocale(), DateFormat.LONG)); } else { @@ -680,9 +669,7 @@ public void doSite(HttpServletRequest req, HttpServletResponse res, Session sess } } - - - doSendResponse(rcontext, res, null); + doSendResponse(rcontext, res); StoredState ss = portalService.getStoredState(); if (ss != null && toolContextPath.equals(ss.getToolContextPath())) @@ -719,7 +706,7 @@ private String findPageIdFromToolId(String pageId, String toolContextPath, } catch (Exception e) { - log.error("exception resolving page id from toolid :["+toolId+"]",e); + log.error("exception resolving page id from toolid :[{}]",toolId, e); } return pageId; @@ -735,9 +722,7 @@ private String findPageIdFromToolId(String pageId, String toolContextPath, * @param b * @throws IOException */ - protected void doSendResponse(PortalRenderContext rcontext, HttpServletResponse res, - String contentType) throws IOException - { + protected void doSendResponse(PortalRenderContext rcontext, HttpServletResponse res) throws IOException { portal.sendResponse(rcontext, res, "site", null); } @@ -746,44 +731,37 @@ protected void includeSiteNav(PortalRenderContext rcontext, HttpServletRequest r if (rcontext.uses(INCLUDE_SITE_NAV)) { boolean loggedIn = session.getUserId() != null; - boolean topLogin = ServerConfigurationService.getBoolean("top.login", true); - String accessibilityURL = ServerConfigurationService.getString("accessibility.url"); + boolean topLogin = serverConfigurationService.getBoolean("top.login", true); + String accessibilityURL = serverConfigurationService.getString("accessibility.url"); - rcontext.put("siteNavHasAccessibilityURL", Boolean.valueOf((accessibilityURL != null && !accessibilityURL.equals("")))); + rcontext.put("siteNavHasAccessibilityURL", accessibilityURL != null && !accessibilityURL.isEmpty()); rcontext.put("siteNavAccessibilityURL", accessibilityURL); - rcontext.put("siteNavTopLogin", Boolean.valueOf(topLogin)); - rcontext.put("siteNavLoggedIn", Boolean.valueOf(loggedIn)); + rcontext.put("siteNavTopLogin", topLogin); + rcontext.put("siteNavLoggedIn", loggedIn); rcontext.put("currentSiteId", siteId); rcontext.put("sidebarSites", portal.getSiteHelper().getContextSitesWithPages(req, siteId, null, loggedIn)); - try - { - if (loggedIn) - { - includeLogo(rcontext, req, session, siteId); + try { + includeLogo(rcontext, req, session, siteId); + if (loggedIn) { includeTabs(rcontext, req, session, siteId, toolId, getUrlFragment(), false); - rcontext.put("picEditorEnabled", imageLogic.isPicEditorEnabled()); - } - else - { - includeLogo(rcontext, req, session, siteId); - if (portal.getSiteHelper().doGatewaySiteList()) + rcontext.put("picEditorEnabled", profileImageLogic.isPicEditorEnabled()); + } else { + if (portal.getSiteHelper().doGatewaySiteList()) { includeTabs(rcontext, req, session, siteId, toolId, getUrlFragment(), false); + } } - } - catch (Exception e) - { + } catch (Exception e) { log.warn("constructing logo and tabs, {}", e.toString()); } } } - public void includeLogo(PortalRenderContext rcontext, HttpServletRequest req, Session session, String siteId) throws IOException - { + public void includeLogo(PortalRenderContext rcontext, HttpServletRequest req, Session session, String siteId) { if (rcontext.uses(INCLUDE_LOGO)) { String skin = getSiteSkin(siteId); - String skinRepo = ServerConfigurationService.getString("skin.repo"); + String skinRepo = serverConfigurationService.getString("skin.repo"); rcontext.put("logoSkin", skin); rcontext.put("logoSkinRepo", skinRepo); portal.includeLogin(rcontext, req, session); @@ -793,26 +771,26 @@ public void includeLogo(PortalRenderContext rcontext, HttpServletRequest req, Se private String getSiteSkin(String siteId) { // First, try to get the skin the default way - String skin = SiteService.getSiteSkin(siteId); + String skin = siteService.getSiteSkin(siteId); // If this fails, try to get the real site id if the site is a user site - if (skin == null && SiteService.isUserSite(siteId)) + if (skin == null && siteService.isUserSite(siteId)) { try { - String userId = SiteService.getSiteUserId(siteId); + String userId = siteService.getSiteUserId(siteId); // If the passed siteId is the users EID, convert it to the internal ID. // Most lookups should be EID, if most URLs contain internal ID, this results in lots of cache misses. try { - userId = UserDirectoryService.getUserId(userId); + userId = userDirectoryService.getUserId(userId); } catch (UserNotDefinedException unde) { // Ignore } - String alternateSiteId = SiteService.getUserSiteId(userId); - skin = SiteService.getSiteSkin(alternateSiteId); + String alternateSiteId = siteService.getUserSiteId(userId); + skin = siteService.getSiteSkin(alternateSiteId); } catch (Exception e) { @@ -822,15 +800,13 @@ private String getSiteSkin(String siteId) if (skin == null) { - skin = ServerConfigurationService.getString("skin.default"); + skin = serverConfigurationService.getString("skin.default"); } return skin; } public void includeTabs(PortalRenderContext rcontext, HttpServletRequest req, - Session session, String siteId, String toolId, String prefix, boolean addLogout) - throws IOException - { + Session session, String siteId, String toolId, String prefix, boolean addLogout) { if (rcontext.uses(INCLUDE_TABS)) { @@ -839,7 +815,7 @@ public void includeTabs(PortalRenderContext rcontext, HttpServletRequest req, // If we have turned on auto-state reset on navigation, we generate // the "site-reset" "worksite-reset" and "gallery-reset" urls - if ("true".equalsIgnoreCase(ServerConfigurationService.getString(Portal.CONFIG_AUTO_RESET))) + if ("true".equalsIgnoreCase(serverConfigurationService.getString(Portal.CONFIG_AUTO_RESET))) { prefix = prefix + "-reset"; } @@ -848,12 +824,12 @@ public void includeTabs(PortalRenderContext rcontext, HttpServletRequest req, // Check to see if we display a link in the UI for swapping the view boolean roleswapcheck = false; // This variable will tell the UI if we will display any role swapping component; false by default - String roleswitchvalue = SecurityService.getUserEffectiveRole(); // checks the session for a role swap value - boolean roleswitchstate = SecurityService.isUserRoleSwapped(); // This variable determines if the site is in the switched state or not; false by default - boolean allowroleswap = SiteService.allowRoleSwap(siteId) && !SecurityService.isSuperUser(); + String roleswitchvalue = securityService.getUserEffectiveRole(); // checks the session for a role swap value + boolean roleswitchstate = securityService.isUserRoleSwapped(); // This variable determines if the site is in the switched state or not; false by default + boolean allowroleswap = siteService.allowRoleSwap(siteId) && !securityService.isSuperUser(); if (roleswitchvalue != null) { - String switchRoleUrl = ServerConfigurationService.getPortalUrl() + String switchRoleUrl = serverConfigurationService.getPortalUrl() + "/role-switch-out/" + siteId + "/tool/" @@ -866,7 +842,7 @@ public void includeTabs(PortalRenderContext rcontext, HttpServletRequest req, // check for the site.roleswap permission else if (allowroleswap) { - Site activeSite = null; + Site activeSite; try { activeSite = portal.getSiteHelper().getSiteVisit(siteId); // active site @@ -887,59 +863,58 @@ else if (allowroleswap) Set roles = activeSite.getRoles(); Role userRole = activeSite.getUserRole(session.getUserId()); // the user's role in the site - String externalRoles = ServerConfigurationService.getString("studentview.roles"); // get the roles that can be swapped to from sakai.properties + String externalRoles = serverConfigurationService.getString("studentview.roles"); // get the roles that can be swapped to from sakai.properties String[] svRoles = externalRoles.split(","); - List svRolesFinal = new ArrayList(); + List svRolesFinal = new ArrayList<>(); for (Role role : roles) { - for (int i = 0; i < svRoles.length; i++) { - if (svRoles[i].trim().equals(role.getId())) { - roleInSite = true; - svRolesFinal.add(role.getId()); - } - } + for (String svRole : svRoles) { + if (svRole.trim().equals(role.getId())) { + roleInSite = true; + svRolesFinal.add(role.getId()); + } + } } // The type check filters out some of non-standard sites where swapping roles would not apply. // The roleInSite check makes sure a role is in the site // The current user role can't be one of the roles to be swapped if (activeSite.getType() != null && roleInSite) { - String switchRoleUrl = ""; - - //if the userRole is null, this means they are more than likely a Delegated Access user. Since the security check has already allowed - //the user to "swaproles" @allowroleswap, we know they have access to this site - if (roleswitchvalue == null) { - if (svRolesFinal.size() > 1) { - rcontext.put("roleswapdropdown", true); - switchRoleUrl = ServerConfigurationService.getPortalUrl() - + "/role-switch/" - + siteId - + "/tool/" - + toolId - + "/"; - - rcontext.put("panelString", "/?panel=Main"); - } else { - rcontext.put("roleswapdropdown", false); - switchRoleUrl = ServerConfigurationService.getPortalUrl() - + "/role-switch/" - + siteId - + "/tool/" - + toolId - + "/" - + svRolesFinal.get(0) - + "/?panel=Main"; - rcontext.put("roleUrlValue", svRolesFinal.get(0)); - } - } - // We'll show the swap role snippet if the current user role is not in "studentview.roles" + String switchRoleUrl; + + // if the userRole is null, this means they are more than likely a Delegated Access user. + // Since the security check has already allowed + // the user to "swaproles" @allowroleswap, we know they have access to this site + if (svRolesFinal.size() > 1) { + rcontext.put("roleswapdropdown", true); + switchRoleUrl = serverConfigurationService.getPortalUrl() + + "/role-switch/" + + siteId + + "/tool/" + + toolId + + "/"; + + rcontext.put("panelString", "/?panel=Main"); + } else { + rcontext.put("roleswapdropdown", false); + switchRoleUrl = serverConfigurationService.getPortalUrl() + + "/role-switch/" + + siteId + + "/tool/" + + toolId + + "/" + + svRolesFinal.get(0) + + "/?panel=Main"; + rcontext.put("roleUrlValue", svRolesFinal.get(0)); + } + // We'll show the swap role snippet if the current user role is not in "studentview.roles" roleswapcheck = !svRolesFinal.contains(userRole.getId()); rcontext.put("siteRoles", svRolesFinal); rcontext.put("switchRoleUrl", switchRoleUrl); } } - rcontext.put("viewAsStudentLink", Boolean.valueOf(roleswapcheck)); // this will tell our UI if we want the link for swapping roles to display + rcontext.put("viewAsStudentLink", roleswapcheck); // this will tell our UI if we want the link for swapping roles to display rcontext.put("roleSwitchState", roleswitchstate); // this will tell our UI if we are in a role swapped state or not int tabDisplayLabel = 1; @@ -950,51 +925,42 @@ else if (allowroleswap) if (loggedIn) { - Preferences prefs = PreferencesService.getPreferences(session.getUserId()); - ResourceProperties props = prefs.getProperties(org.sakaiproject.user.api.PreferencesService.SITENAV_PREFS_KEY); + Preferences prefs = preferencesService.getPreferences(session.getUserId()); + ResourceProperties props = prefs.getProperties(PreferencesService.SITENAV_PREFS_KEY); - try - { + try { tabDisplayLabel = (int) props.getLongProperty("tab:label"); - } - catch (Exception any) - { - tabDisplayLabel = 1; + } catch (Exception e) { + log.debug("no property named tab:label, {}", e.toString()); } try { sidebarCollapsed = props.getBooleanProperty(PortalConstants.PROP_SIDEBAR_COLLAPSED); - } catch (org.sakaiproject.entity.api.EntityPropertyNotDefinedException any) { - sidebarCollapsed = false; - } catch (org.sakaiproject.entity.api.EntityPropertyTypeException any) { - log.warn("Exception caught whilst getting sidebarCollapsed: {}", any.toString()); + } catch (Exception e) { + log.warn("Exception caught whilst getting sidebarCollapsed, {}", e.toString()); } try { currentExpanded = props.getBooleanProperty(PortalConstants.PROP_CURRENT_EXPANDED); expandedSite = props.getProperty(PortalConstants.PROP_EXPANDED_SITE); - } catch (org.sakaiproject.entity.api.EntityPropertyNotDefinedException any) { - currentExpanded = false; - } catch (org.sakaiproject.entity.api.EntityPropertyTypeException any) { - log.warn("Exception caught whilst getting currentExpanded: {}", any.toString()); + } catch (Exception e) { + log.warn("Exception caught whilst getting currentExpanded, {}", e.toString()); } try { toolMaximised = props.getBooleanProperty("toolMaximised"); - } catch (org.sakaiproject.entity.api.EntityPropertyNotDefinedException any) { - toolMaximised = false; - } catch (org.sakaiproject.entity.api.EntityPropertyTypeException any) { - log.warn("Exception caught whilst getting toolMaximised: {}", any.toString()); + } catch (Exception e) { + log.warn("Exception caught whilst getting toolMaximised, {}", e.toString()); } } rcontext.put("tabDisplayLabel", tabDisplayLabel); - rcontext.put(PortalConstants.PROP_SIDEBAR_COLLAPSED, Boolean.valueOf(sidebarCollapsed)); + rcontext.put(PortalConstants.PROP_SIDEBAR_COLLAPSED, sidebarCollapsed); if (expandedSite.equals(siteId)) { - rcontext.put(PortalConstants.PROP_CURRENT_EXPANDED, Boolean.valueOf(currentExpanded)); + rcontext.put(PortalConstants.PROP_CURRENT_EXPANDED, currentExpanded); } - rcontext.put("toolMaximised", Boolean.valueOf(toolMaximised)); + rcontext.put("toolMaximised", toolMaximised); SiteView siteView = portal.getSiteHelper().getSitesView( SiteView.View.DHTML_MORE_VIEW, req, session, siteId); @@ -1005,19 +971,19 @@ else if (allowroleswap) String cssClass = (siteType != null) ? "siteNavWrap " + siteType : "siteNavWrap"; rcontext.put("tabsCssClass", cssClass); - rcontext.put("tabsAddLogout", Boolean.valueOf(addLogout)); + rcontext.put("tabsAddLogout", addLogout); if (addLogout) { String logoutUrl = RequestFilter.serverUrl(req) - + ServerConfigurationService.getString("portalPath") + + serverConfigurationService.getString("portalPath") + "/logout_gallery"; rcontext.put("tabsLogoutUrl", logoutUrl); } boolean allowAddSite = false; - if(SiteService.allowAddCourseSite()) { + if(siteService.allowAddCourseSite()) { allowAddSite = true; - } else if (SiteService.allowAddProjectSite()) { + } else if (siteService.allowAddProjectSite()) { allowAddSite = true; } @@ -1034,13 +1000,13 @@ public boolean checkBufferBypass(HttpServletRequest req, ToolConfiguration siteT String commonToolId = siteTool.getToolId(); boolean matched = false; // Check the URL for a pattern match - String pattern = null; - Pattern p = null; - Matcher m = null; - pattern = ServerConfigurationService .getString(LEGACY_BYPASS_URL_PROP, DEFAULT_BYPASS_URL); - pattern = ServerConfigurationService .getString(BYPASS_URL_PROP, pattern); - pattern = ServerConfigurationService .getString(LEGACY_BYPASS_URL_PROP+"."+commonToolId, pattern); - pattern = ServerConfigurationService .getString(BYPASS_URL_PROP+"."+commonToolId, pattern); + String pattern; + Pattern p; + Matcher m; + pattern = serverConfigurationService.getString(LEGACY_BYPASS_URL_PROP, DEFAULT_BYPASS_URL); + pattern = serverConfigurationService.getString(BYPASS_URL_PROP, pattern); + pattern = serverConfigurationService.getString(LEGACY_BYPASS_URL_PROP + "." + commonToolId, pattern); + pattern = serverConfigurationService.getString(BYPASS_URL_PROP + "." + commonToolId, pattern); if ( pattern.length() > 1 ) { p = Pattern.compile(pattern); m = p.matcher(uri.toLowerCase()); @@ -1050,10 +1016,10 @@ public boolean checkBufferBypass(HttpServletRequest req, ToolConfiguration siteT } // Check the query string for a pattern match - pattern = ServerConfigurationService .getString(LEGACY_BYPASS_QUERY_PROP, DEFAULT_BYPASS_QUERY); - pattern = ServerConfigurationService .getString(BYPASS_QUERY_PROP, pattern); - pattern = ServerConfigurationService .getString(LEGACY_BYPASS_QUERY_PROP+"."+commonToolId, pattern); - pattern = ServerConfigurationService .getString(BYPASS_QUERY_PROP+"."+commonToolId, pattern); + pattern = serverConfigurationService.getString(LEGACY_BYPASS_QUERY_PROP, DEFAULT_BYPASS_QUERY); + pattern = serverConfigurationService.getString(BYPASS_QUERY_PROP, pattern); + pattern = serverConfigurationService.getString(LEGACY_BYPASS_QUERY_PROP + "." + commonToolId, pattern); + pattern = serverConfigurationService.getString(BYPASS_QUERY_PROP + "." + commonToolId, pattern); String queryString = req.getQueryString(); if ( queryString == null ) queryString = ""; if ( pattern.length() > 1 ) { @@ -1064,8 +1030,7 @@ public boolean checkBufferBypass(HttpServletRequest req, ToolConfiguration siteT } } - // wicket-ajax request can not be buffered (PRFL-405) - if (Boolean.valueOf(req.getHeader("wicket-ajax"))) { + if (Boolean.parseBoolean(req.getHeader("wicket-ajax"))) { matched = true; } return matched; @@ -1074,37 +1039,30 @@ public boolean checkBufferBypass(HttpServletRequest req, ToolConfiguration siteT /* * Check to see if this tool allows the buffering of content */ - public boolean allowBufferContent(HttpServletRequest req, Site site, ToolConfiguration siteTool) - { - String tidAllow = ServerConfigurationService.getString(LEGACY_IFRAME_SUPPRESS_PROP, IFRAME_SUPPRESS_DEFAULT); - tidAllow = ServerConfigurationService.getString(IFRAME_SUPPRESS_PROP, tidAllow); + public boolean allowBufferContent(Site site, ToolConfiguration siteTool) { + String tidAllow = serverConfigurationService.getString(LEGACY_IFRAME_SUPPRESS_PROP, IFRAME_SUPPRESS_DEFAULT); + tidAllow = serverConfigurationService.getString(IFRAME_SUPPRESS_PROP, tidAllow); - if (tidAllow.indexOf(":none:") >= 0) return false; + if (tidAllow.contains(":none:")) return false; // JSR-168 portlets do not operate in iframes if ( portal.isPortletPlacement(siteTool) ) return false; // If the property is set and :all: is not specified, then the // tools in the list are the ones that we accept - if (tidAllow.trim().length() > 0 && tidAllow.indexOf(":all:") < 0) - { - if (tidAllow.indexOf(siteTool.getToolId()) < 0) return false; + if (!tidAllow.trim().isEmpty() && !tidAllow.contains(":all:")) { + if (!tidAllow.contains(siteTool.getToolId())) return false; } // If the property is set and :all: is specified, then the // tools in the list are the ones that we render the old way - if (tidAllow.indexOf(":all:") >= 0) - { - if (tidAllow.indexOf(siteTool.getToolId()) >= 0) return false; + if (tidAllow.contains(":all:")) { + if (tidAllow.contains(siteTool.getToolId())) return false; } // Need to make sure the user is allowed to visit this tool - ToolManager toolManager = (ToolManager) ComponentManager.get(ToolManager.class.getName()); - boolean allowedUser = toolManager.allowTool(site, siteTool); - if ( ! allowedUser ) return false; - - return true; - } + return toolManager.allowTool(site, siteTool); + } /* * Optionally actually grab the tool's output and include it in the same @@ -1124,11 +1082,11 @@ public Object bufferContent(HttpServletRequest req, HttpServletResponse res, try { // Prepare the session for the tools. Handles session reset, reseturl // and helpurl for neo tools - we don't need the returned map - Map discard = portal.includeTool(res, req, siteTool, true); + portal.includeTool(res, req, siteTool, true); boolean retval = doToolBuffer(req, bufferedResponse, session, placementId, toolContextPath, toolPathInfo); - log.debug("bufferContent retval="+retval); + log.debug("bufferContent retval={}", retval); if ( ! retval ) return Boolean.FALSE; @@ -1137,11 +1095,11 @@ public Object bufferContent(HttpServletRequest req, HttpServletResponse res, // Check the response contentType for a pattern match String commonToolId = siteTool.getToolId(); - String pattern = ServerConfigurationService .getString(LEGACY_BYPASS_TYPE_PROP, DEFAULT_BYPASS_TYPE); - pattern = ServerConfigurationService .getString(BYPASS_TYPE_PROP, pattern); - pattern = ServerConfigurationService .getString(LEGACY_BYPASS_TYPE_PROP+"."+commonToolId, pattern); - pattern = ServerConfigurationService .getString(BYPASS_TYPE_PROP+"."+commonToolId, pattern); - if ( pattern.length() > 0 ) { + String pattern = serverConfigurationService .getString(LEGACY_BYPASS_TYPE_PROP, DEFAULT_BYPASS_TYPE); + pattern = serverConfigurationService.getString(BYPASS_TYPE_PROP, pattern); + pattern = serverConfigurationService.getString(LEGACY_BYPASS_TYPE_PROP + "." + commonToolId, pattern); + pattern = serverConfigurationService.getString(BYPASS_TYPE_PROP + "." + commonToolId, pattern); + if (!pattern.isEmpty()) { String contentType = res.getContentType(); if ( contentType == null ) contentType = ""; Pattern p = Pattern.compile(pattern); @@ -1152,14 +1110,14 @@ public Object bufferContent(HttpServletRequest req, HttpServletResponse res, log.warn("Failed to buffer content.", e); return Boolean.FALSE; } - String tidAllow = ServerConfigurationService.getString(LEGACY_IFRAME_SUPPRESS_PROP, IFRAME_SUPPRESS_DEFAULT); - tidAllow = ServerConfigurationService.getString(IFRAME_SUPPRESS_PROP, tidAllow); + String tidAllow = serverConfigurationService.getString(LEGACY_IFRAME_SUPPRESS_PROP, IFRAME_SUPPRESS_DEFAULT); + tidAllow = serverConfigurationService.getString(IFRAME_SUPPRESS_PROP, tidAllow); boolean debug = tidAllow.contains(":debug:"); String responseStr = bufferedResponse.getInternalBuffer(); - if (responseStr == null || responseStr.length() < 1) return Boolean.FALSE; + if (responseStr == null || responseStr.isEmpty()) return Boolean.FALSE; - PageParts pp = parseHtmlParts(responseStr, debug); + PageParts pp = parseHtmlParts(responseStr); if (pp != null) { if (debug) @@ -1191,11 +1149,9 @@ static class PageParts { /** * Attempts to find the HTML head and body in the document and return them back. * @param responseStr The HTML to be parse - * @param debug If true then log where we found the head and body. - * * @return null if we failed to parse the page or a PageParts object. */ - PageParts parseHtmlParts(String responseStr, boolean debug) { + PageParts parseHtmlParts(String responseStr) { // We can't lowercase the string and search in it as then the offsets don't match when a character is a // different length in upper and lower case int headStart = StringUtils.indexOfIgnoreCase(responseStr, " bodyStart && bodyStart > headEnd && headEnd > headStart && headStart > 1) { @@ -1257,14 +1212,14 @@ public boolean doToolBuffer(HttpServletRequest req, HttpServletResponse res, if (portal.redirectIfLoggedOut(res)) return false; // find the tool from some site - ToolConfiguration siteTool = SiteService.findTool(placementId); + ToolConfiguration siteTool = siteService.findTool(placementId); if (siteTool == null) { return false; } // find the tool registered for this - ActiveTool tool = ActiveToolManager.getActiveTool(siteTool.getToolId()); + ActiveTool tool = toolManager.getActiveTool(siteTool.getToolId()); if (tool == null) { return false; @@ -1277,7 +1232,7 @@ public boolean doToolBuffer(HttpServletRequest req, HttpServletResponse res, try { - SiteService.getSiteVisit(siteTool.getSiteId()); + siteService.getSiteVisit(siteTool.getSiteId()); } catch (IdUnusedException e) { @@ -1290,10 +1245,9 @@ public boolean doToolBuffer(HttpServletRequest req, HttpServletResponse res, } } - log.debug("doToolBuffer siteTool="+siteTool+" TCP="+toolContextPath+" TPI="+toolPathInfo); + log.debug("doToolBuffer siteTool={} TCP={} TPI={}", siteTool, toolContextPath, toolPathInfo); - portal.forwardTool(tool, req, res, siteTool, siteTool.getSkin(), toolContextPath, - toolPathInfo); + portal.forwardTool(tool, req, res, siteTool, siteTool.getSkin(), toolContextPath, toolPathInfo); return true; } diff --git a/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/PortalTestConfiguration.java b/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/PortalTestConfiguration.java new file mode 100644 index 000000000000..4a97d3c886fa --- /dev/null +++ b/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/PortalTestConfiguration.java @@ -0,0 +1,99 @@ +package org.sakaiproject.portal.charon; + +import org.mockito.Mockito; +import org.sakaiproject.authz.api.SecurityService; +import org.sakaiproject.component.api.ServerConfigurationService; +import org.sakaiproject.coursemanagement.api.CourseManagementService; +import org.sakaiproject.event.api.EventTrackingService; +import org.sakaiproject.presence.api.PresenceService; +import org.sakaiproject.profile2.logic.ProfileImageLogic; +import org.sakaiproject.site.api.SiteService; +import org.sakaiproject.thread_local.api.ThreadLocalManager; +import org.sakaiproject.time.api.TimeService; +import org.sakaiproject.time.api.UserTimeService; +import org.sakaiproject.tool.api.ActiveToolManager; +import org.sakaiproject.tool.api.SessionManager; +import org.sakaiproject.user.api.PreferencesService; +import org.sakaiproject.user.api.UserDirectoryService; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import static org.mockito.Mockito.mock; + +@Configuration +public class PortalTestConfiguration { + + @Bean(name = "org.sakaiproject.tool.api.ActiveToolManager") + public ActiveToolManager activeToolManager() { + return mock(ActiveToolManager.class); + } + + @Bean(name = "org.sakaiproject.coursemanagement.api.CourseManagementService") + public CourseManagementService courseManagementService() { + return mock(CourseManagementService.class); + } + + @Bean(name = "org.sakaiproject.event.api.EventTrackingService") + public EventTrackingService eventTrackingService() { + return mock(EventTrackingService.class); + } + + @Bean(name = "org.sakaiproject.user.api.PreferencesService") + public PreferencesService preferencesService() { + return mock(PreferencesService.class); + } + + @Bean(name = "org.sakaiproject.presence.api.PresenceService") + public PresenceService presenceService() { + return mock(PresenceService.class); + } + + @Bean(name = "org.sakaiproject.profile2.logic.ProfileImageLogic") + public ProfileImageLogic profileImageLogic() { + return mock(ProfileImageLogic.class); + } + + @Bean(name = "org.sakaiproject.authz.api.SecurityService") + public SecurityService securityService() { + return mock(SecurityService.class); + } + + @Bean(name = "org.sakaiproject.component.api.ServerConfigurationService") + public ServerConfigurationService serverConfigurationService() { + ServerConfigurationService scs = mock(ServerConfigurationService.class); + Mockito.when(scs.getString("portal.mutable.sitename", "-")).thenReturn("-"); + Mockito.when(scs.getString("portal.mutable.pagename", "-")).thenReturn("-"); + return scs; + } + + @Bean(name = "org.sakaiproject.tool.api.SessionManager") + public SessionManager sessionManager() { + return mock(SessionManager.class); + } + + @Bean(name = "org.sakaiproject.site.api.SiteService") + public SiteService siteService() { + return mock(SiteService.class); + } + + @Bean(name = "org.sakaiproject.thread_local.api.ThreadLocalManager") + public ThreadLocalManager threadLocalManager() { + return mock(ThreadLocalManager.class); + } + + @Bean(name = "org.sakaiproject.time.api.TimeService") + public TimeService timeService() { + return mock(TimeService.class); + } + + @Bean(name = "org.sakaiproject.user.api.UserDirectoryService") + public UserDirectoryService userDirectoryService() { + return mock(UserDirectoryService.class); + } + + @Bean(name = "org.sakaiproject.time.api.UserTimeService") + public UserTimeService userTimeService() { + return mock(UserTimeService.class); + } + +} diff --git a/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/handlers/SiteHandlerTest.java b/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/handlers/SiteHandlerTest.java index d542a9a30753..56a87cadcbc7 100644 --- a/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/handlers/SiteHandlerTest.java +++ b/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/handlers/SiteHandlerTest.java @@ -15,42 +15,68 @@ */ package org.sakaiproject.portal.charon.handlers; -import junit.framework.Assert; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; import org.sakaiproject.component.cover.ComponentManager; +import org.sakaiproject.portal.charon.PortalTestConfiguration; import org.sakaiproject.time.api.TimeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.AbstractApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.context.ContextLoader; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.support.GenericWebApplicationContext; -import static org.sakaiproject.portal.charon.handlers.SiteHandler.*; +import javax.servlet.ServletContext; +import java.util.Collections; -/** - * Tests for SiteHandler - */ -@RunWith(PowerMockRunner.class) -@PrepareForTest(ComponentManager.class) +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.sakaiproject.portal.charon.handlers.SiteHandler.PageParts; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {PortalTestConfiguration.class}) public class SiteHandlerTest { + public static boolean setupOnceCompleted = false; + + @Autowired private ApplicationContext applicationContext; + @Autowired private TimeService timeService; + private SiteHandler siteHandler; - private boolean debug; @Before public void setUp() { - debug = false; - PowerMockito.mockStatic(ComponentManager.class); - TimeService timeService = Mockito.mock(TimeService.class); - Mockito.when(ComponentManager.get(TimeService.class)).thenReturn(timeService); - siteHandler = new SiteHandler(); + if (!setupOnceCompleted) { + // Setup a fake webapp so spring injection will happen + ServletContext servletContext = mock(ServletContext.class); + Mockito.when(servletContext.getInitParameterNames()).thenReturn(Collections.emptyEnumeration()); + Mockito.when(servletContext.getAttributeNames()).thenReturn(Collections.emptyEnumeration()); + + WebApplicationContext webApplicationContext = new GenericWebApplicationContext(servletContext); + ((AbstractApplicationContext) webApplicationContext).setParent(applicationContext); + ContextLoader contextLoader = new ContextLoader(webApplicationContext); + contextLoader.initWebApplicationContext(servletContext); + + setupOnceCompleted = true; + } + + try (MockedStatic cm = mockStatic(ComponentManager.class)) { + cm.when(() -> ComponentManager.get(TimeService.class)).thenReturn(timeService); + siteHandler = new SiteHandler(); + } } @Test public void testParseHtmlSimple() { - PageParts pp = siteHandler.parseHtmlParts("Hello

Hello World

", debug); + PageParts pp = siteHandler.parseHtmlParts("Hello

Hello World

"); Assert.assertNotNull(pp); Assert.assertEquals("", pp.head); Assert.assertEquals("

Hello World

", pp.body); @@ -58,7 +84,7 @@ public void testParseHtmlSimple() { @Test public void testParseHtmlStyle() { - PageParts pp = siteHandler.parseHtmlParts("Hello

Hello World

", debug); + PageParts pp = siteHandler.parseHtmlParts("Hello

Hello World

"); Assert.assertNotNull(pp); Assert.assertEquals("", pp.head); Assert.assertEquals("

Hello World

", pp.body); @@ -66,13 +92,13 @@ public void testParseHtmlStyle() { @Test public void testParseHtmlNoHead() { - PageParts pp = siteHandler.parseHtmlParts("

Hello World

", debug); + PageParts pp = siteHandler.parseHtmlParts("

Hello World

"); Assert.assertNull(pp); } @Test public void testParseHtmlNoBody() { - PageParts pp = siteHandler.parseHtmlParts("Hello", debug); + PageParts pp = siteHandler.parseHtmlParts("Hello"); Assert.assertNull(pp); } @@ -81,7 +107,7 @@ public void testParseHtmlLowercaseUnicode() { // When this HTML fragment is lowercased it becomes longer (more bytes in the string) so the offsets can // become incorrect causing a stack trace (stack overflow). The test has enough extra bytes to overflow // past the end of the string. - PageParts pp = siteHandler.parseHtmlParts("Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°", debug); + PageParts pp = siteHandler.parseHtmlParts("Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°"); Assert.assertNotNull(pp); Assert.assertEquals("", pp.head); Assert.assertEquals("Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°Ä°", pp.body); diff --git a/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/site/PortalSiteHelperTest.java b/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/site/PortalSiteHelperTest.java deleted file mode 100644 index 165d30c52e31..000000000000 --- a/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/site/PortalSiteHelperTest.java +++ /dev/null @@ -1,15 +0,0 @@ -/** - * Copyright (c) 2003-2014 The Apereo Foundation - * - * Licensed under the Educational Community License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://opensource.org/licenses/ecl2 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ diff --git a/portal/portal-render-engine-impl/impl/src/webapp/vm/morpheus/snippets/siteStatus-snippet.vm b/portal/portal-render-engine-impl/impl/src/webapp/vm/morpheus/snippets/siteStatus-snippet.vm index ff1ad2372975..38b94e5f27f8 100644 --- a/portal/portal-render-engine-impl/impl/src/webapp/vm/morpheus/snippets/siteStatus-snippet.vm +++ b/portal/portal-render-engine-impl/impl/src/webapp/vm/morpheus/snippets/siteStatus-snippet.vm @@ -16,7 +16,9 @@ #else ${rloader.sit_unpublished} #end + #if($publishSiteButton) + #end ##if($manageurl) ## ${rloader.sit_managepublish} ##end diff --git a/portal/portal-service-impl/impl/src/java/org/sakaiproject/portal/service/PortalServiceImpl.java b/portal/portal-service-impl/impl/src/java/org/sakaiproject/portal/service/PortalServiceImpl.java index 39776fa53447..abd533998029 100644 --- a/portal/portal-service-impl/impl/src/java/org/sakaiproject/portal/service/PortalServiceImpl.java +++ b/portal/portal-service-impl/impl/src/java/org/sakaiproject/portal/service/PortalServiceImpl.java @@ -115,10 +115,10 @@ public class PortalServiceImpl implements PortalService, Observer @Setter private SiteNeighbourhoodService siteNeighbourhoodService; @Setter private SiteService siteService; - private Map> handlerMaps = new ConcurrentHashMap<>(); - private Editor noopEditor = new BaseEditor("noop", "noop", "", ""); - private Map portals = new ConcurrentHashMap<>(); - private Map renderEngines = new ConcurrentHashMap<>(); + private final Map> handlerMaps = new ConcurrentHashMap<>(); + private final Editor noopEditor = new BaseEditor("noop", "noop", "", ""); + private final Map portals = new ConcurrentHashMap<>(); + private final Map renderEngines = new ConcurrentHashMap<>(); public void init() { try { @@ -127,7 +127,7 @@ public void init() { String parser = serverConfigurationService.getString( "sakai.xml.sax.parser", "com.sun.org.apache.xerces.internal.parsers.SAXParser"); - log.info("Configured Castor to use SAX Parser " + parser); + log.info("Configured Castor to use SAX Parser {}", parser); castorProperties.put(Property.Parser, parser); } catch (Exception ex) { log.warn("Failed to configure Castor, {}", ex.toString()); @@ -302,7 +302,7 @@ public String decodeToolState(Map params, String placementId) public Map encodeToolState(String placementId, String URLstub) { String attrname = computeToolStateParameterName(placementId); - Map togo = new HashMap(); + Map togo = new HashMap<>(); // could assemble state from other visible tools here togo.put(attrname, new String[] { URLstub }); return togo; @@ -363,130 +363,99 @@ public Iterator getRegisteredApplications() { PortletRegistryService registry = PortletContextManager.getManager(); final Iterator apps = registry.getRegisteredPortletApplications(); - return new Iterator() - { + return new Iterator<>() { - public boolean hasNext() - { - return apps.hasNext(); - } + public boolean hasNext() { + return apps.hasNext(); + } - public PortletApplicationDescriptor next() - { - final InternalPortletContext pc = (InternalPortletContext) apps.next(); + public PortletApplicationDescriptor next() { + final InternalPortletContext pc = (InternalPortletContext) apps.next(); - final PortletAppDD appDD = pc.getPortletApplicationDefinition(); - return new PortletApplicationDescriptor() - { + final PortletAppDD appDD = pc.getPortletApplicationDefinition(); + return new PortletApplicationDescriptor() { - public String getApplicationContext() - { - return pc.getPortletContextName(); - } + public String getApplicationContext() { + return pc.getPortletContextName(); + } - public String getApplicationId() - { - return pc.getApplicationId(); - } + public String getApplicationId() { + return pc.getApplicationId(); + } - public String getApplicationName() - { - return pc.getApplicationId(); - } + public String getApplicationName() { + return pc.getApplicationId(); + } - public Iterator getPortlets() - { - if (appDD != null) - { - List portlets = appDD.getPortlets(); + public Iterator getPortlets() { + if (appDD != null) { + List portlets = appDD.getPortlets(); - final Iterator portletsI = portlets.iterator(); - return new Iterator() - { + final Iterator portletsI = portlets.iterator(); + return new Iterator<>() { - public boolean hasNext() - { - return portletsI.hasNext(); - } + public boolean hasNext() { + return portletsI.hasNext(); + } - public PortletDescriptor next() - { - final PortletDD pdd = (PortletDD) portletsI.next(); - return new PortletDescriptor() - { + public PortletDescriptor next() { + final PortletDD pdd = (PortletDD) portletsI.next(); + return new PortletDescriptor() { - public String getPortletId() - { - return pdd.getPortletName(); - } + public String getPortletId() { + return pdd.getPortletName(); + } - public String getPortletName() - { - return pdd.getPortletName(); - } + public String getPortletName() { + return pdd.getPortletName(); + } - }; - } + }; + } - public void remove() - { - } + public void remove() { + } - }; - } - else - { - log.warn(" Portlet Application has no portlets " - + pc.getPortletContextName()); - return new Iterator() - { - - public boolean hasNext() - { - return false; - } + }; + } else { + log.warn(" Portlet Application has no portlets {}", pc.getPortletContextName()); + return new Iterator<>() { - public PortletDescriptor next() - { - return null; - } + public boolean hasNext() { + return false; + } - public void remove() - { - } + public PortletDescriptor next() { + return null; + } - }; - } - } + public void remove() { + } - }; - } + }; + } + } - public void remove() - { - } + }; + } + + public void remove() { + } - }; + }; } @Override - public PortalRenderEngine getRenderEngine(String context, HttpServletRequest request) - { - // at this point we ignore request but we might use ut to return more - // than one render engine - - if (context == null || context.length() == 0) - { + public PortalRenderEngine getRenderEngine(String context, HttpServletRequest request) { + if (context == null || context.isEmpty()) { context = Portal.DEFAULT_PORTAL_CONTEXT; } - return (PortalRenderEngine) renderEngines.get(context); + return renderEngines.get(context); } @Override - public void addRenderEngine(String context, PortalRenderEngine vengine) - { - + public void addRenderEngine(String context, PortalRenderEngine vengine) { renderEngines.put(context, vengine); } @@ -545,7 +514,7 @@ private Map getHandlerMap(String portalContext, boolean c Map handlerMap = handlerMaps.get(portalContext); if (create && handlerMap == null) { - handlerMap = new ConcurrentHashMap(); + handlerMap = new ConcurrentHashMap<>(); handlerMaps.put(portalContext, handlerMap); } return handlerMap; @@ -589,12 +558,9 @@ public void addPortal(Portal portal) portals.put(portalContext, portal); // reconnect any handlers Map phm = getHandlerMap(portal); - for (Iterator pIterator = phm.values().iterator(); pIterator - .hasNext();) - { - PortalHandler ph = pIterator.next(); - ph.register(portal, this, portal.getServletContext()); - } + for (PortalHandler ph : phm.values()) { + ph.register(portal, this, portal.getServletContext()); + } } @Override @@ -608,25 +574,9 @@ public void removePortal(Portal portal) public String getContentItemUrl(Site site) { if ( site == null ) return null; - ToolConfiguration toolConfig = site.getToolForCommonId("sakai.siteinfo"); - - if (toolConfig == null) return null; - - // SAK-32656 For now we always show the cart. - // Un-comment these lines to make the cart only appear when tools are - // available at a cost of one SQL query per request/response cycle. - - /* - // Check if we have any registered ContentItem editor tools - LTIService ltiService = (LTIService) ComponentManager.get("org.sakaiproject.lti.api.LTIService"); - - List> toolsContentItem = ltiService.getToolsContentEditor(placement.getContext()); - if ( toolsContentItem.size() < 1 ) return null; - */ - - // Now we are in good shape, make the URL - String helper_url = "/portal/tool/"+toolConfig.getId()+"/sakai.lti.admin.helper.helper?panel=CKEditor"; - return helper_url; + ToolConfiguration toolConfig = site.getToolForCommonId("sakai.siteinfo"); + if (toolConfig == null) return null; + return "/portal/tool/" + toolConfig.getId() + "/sakai.lti.admin.helper.helper?panel=CKEditor"; } @Override @@ -701,14 +651,14 @@ public String getQuickLinksTitle(String siteSkin) { @Override public List getQuickLinks(String siteSkin){ - /* Find the quick links (if they are in the properties file) ready for display in the top navigation bar. - * First try with the skin name as there may be different quick links per site, then try with no skin. */ + // Find the quick links (if they are in the properties file) ready for display in the top navigation bar. + // First try with the skin name as there may be different quick links per site, then try with no skin. List linkUrls = null; List linkTitles = null; ListlinkNames = null; List linkIcons = null; - //A null check really isn't needed here sin siteSkin should always be set (or it can just turn into the string "null") but it's here anyway) + // A null check really isn't needed here sin siteSkin should always be set (or it can just turn into the string "null") but it's here anyway if (siteSkin != null) { linkUrls = Arrays.asList(ArrayUtils.nullToEmpty(serverConfigurationService.getStrings("portal.quicklink." + siteSkin + ".url"))); linkTitles = Arrays.asList(ArrayUtils.nullToEmpty(serverConfigurationService.getStrings("portal.quicklink." + siteSkin + ".title"))); @@ -717,18 +667,18 @@ public List getQuickLinks(String siteSkin){ } //However if it is null or if the linkUrls was empty from before, just use the default - if (siteSkin == null || (siteSkin != null && linkUrls.isEmpty())) { + if (siteSkin == null || linkUrls.isEmpty()) { linkUrls = Arrays.asList(ArrayUtils.nullToEmpty(serverConfigurationService.getStrings("portal.quicklink.url"))); linkTitles = Arrays.asList(ArrayUtils.nullToEmpty(serverConfigurationService.getStrings("portal.quicklink.title"))); linkNames = Arrays.asList(ArrayUtils.nullToEmpty(serverConfigurationService.getStrings("portal.quicklink.name"))); linkIcons = Arrays.asList(ArrayUtils.nullToEmpty(serverConfigurationService.getStrings("portal.quicklink.icon"))); } - List quickLinks = new ArrayList(linkUrls.size()); + List quickLinks = new ArrayList<>(linkUrls.size()); if (!linkUrls.isEmpty()) { if (linkUrls.size() != linkTitles.size() || linkUrls.size() != linkNames.size() || linkUrls.size() != linkIcons.size()) { log.info("All portal.quicklink variables must be defined and the same size for quick links feature to work. One or more is not configured correctly."); - return new ArrayList(); + return new ArrayList<>(); } for (int i = 0; i < linkUrls.size(); i++) { String url = linkUrls.get(i); @@ -737,7 +687,7 @@ public List getQuickLinks(String siteSkin){ String icon = linkIcons.get(i); if (url != null) { - Map linkDetails = new HashMap(); + Map linkDetails = new HashMap<>(); linkDetails.put("url", url); if (name != null) { linkDetails.put("name", name); From 4accdd3ae65fc67eb790a19b7bc2cbbad7e62a99 Mon Sep 17 00:00:00 2001 From: Earle Nietzel Date: Sun, 25 Aug 2024 23:31:12 -0400 Subject: [PATCH 2/2] more service clean up in handlers --- portal/portal-impl/impl/pom.xml | 4 +- .../charon/handlers/BasePortalHandler.java | 20 +- .../charon/handlers/DirectToolHandler.java | 9 +- .../portal/charon/handlers/JoinHandler.java | 21 ++- .../portal/charon/handlers/PageHandler.java | 10 +- .../charon/handlers/RoleSwitchOutHandler.java | 16 +- .../portal/charon/handlers/SiteHandler.java | 11 +- .../charon/handlers/TimeoutDialogHandler.java | 13 +- .../charon/site/AbstractSiteViewImpl.java | 146 +++------------ .../portal/charon/site/AllSitesViewImpl.java | 30 +-- .../charon/site/CurrentSiteViewImpl.java | 166 ++++------------- .../charon/site/DefaultSiteViewImpl.java | 95 ++-------- .../portal/charon/site/MoreSiteViewImpl.java | 89 ++------- .../charon/site/PortalSiteHelperImpl.java | 176 +++++------------- .../charon/PortalTestConfiguration.java | 17 +- .../charon/handlers/SiteHandlerTest.java | 10 +- .../charon/handlers/StaticHandlerTest.java | 83 ++++++--- 17 files changed, 277 insertions(+), 639 deletions(-) diff --git a/portal/portal-impl/impl/pom.xml b/portal/portal-impl/impl/pom.xml index e592c336e380..a2333d5debd3 100644 --- a/portal/portal-impl/impl/pom.xml +++ b/portal/portal-impl/impl/pom.xml @@ -144,9 +144,7 @@ org.mockito - mockito-inline - 3.7.0 - test + mockito-core diff --git a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/BasePortalHandler.java b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/BasePortalHandler.java index 1d036e545a28..70aaee908036 100644 --- a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/BasePortalHandler.java +++ b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/BasePortalHandler.java @@ -38,11 +38,13 @@ import org.sakaiproject.portal.api.PortalService; import org.sakaiproject.portal.util.PortalUtils; import org.sakaiproject.site.api.Site; -import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.time.api.TimeService; +import org.sakaiproject.time.api.UserTimeService; import org.sakaiproject.tool.api.Session; import org.sakaiproject.util.ResourceLoader; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; /** @@ -54,15 +56,8 @@ * */ @Slf4j -public abstract class BasePortalHandler implements PortalHandler -{ - public BasePortalHandler() - { - urlFragment = "none"; - timeService = ComponentManager.get(TimeService.class); - } - - private TimeService timeService; +public abstract class BasePortalHandler implements PortalHandler { + @Autowired UserTimeService timeService; protected PortalService portalService; @@ -72,6 +67,11 @@ public BasePortalHandler() protected ServletContext servletContext; + public BasePortalHandler() { + SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); + urlFragment = "none"; + } + public abstract int doGet(String[] parts, HttpServletRequest req, HttpServletResponse res, Session session) throws PortalHandlerException; diff --git a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/DirectToolHandler.java b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/DirectToolHandler.java index a2e5302fc91b..fa580e49ea22 100644 --- a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/DirectToolHandler.java +++ b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/DirectToolHandler.java @@ -42,9 +42,10 @@ import org.sakaiproject.tool.cover.ActiveToolManager; import org.sakaiproject.tool.cover.SessionManager; import org.sakaiproject.util.Web; -import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.component.api.ServerConfigurationService; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; /** * Handler to process directtool urls including storing destination state @@ -57,12 +58,12 @@ @Slf4j public class DirectToolHandler extends BasePortalHandler { - private static ServerConfigurationService serverConfigurationService = (ServerConfigurationService)ComponentManager.get(ServerConfigurationService.class); + @Autowired private ServerConfigurationService serverConfigurationService; public static final String URL_FRAGMENT = "directtool"; - public DirectToolHandler() - { + public DirectToolHandler() { + SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); setUrlFragment(DirectToolHandler.URL_FRAGMENT); } diff --git a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/JoinHandler.java b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/JoinHandler.java index 03015450cadf..ec0191a45f0f 100644 --- a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/JoinHandler.java +++ b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/JoinHandler.java @@ -21,18 +21,20 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.sakaiproject.authz.api.AuthzGroupService; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.portal.api.Portal; import org.sakaiproject.portal.api.PortalHandlerException; import org.sakaiproject.portal.api.PortalRenderContext; -import org.sakaiproject.portal.charon.site.PortalSiteHelperImpl; import org.sakaiproject.site.api.Site; -import org.sakaiproject.site.cover.SiteService; +import org.sakaiproject.site.api.SiteService; import org.sakaiproject.tool.api.Session; import org.sakaiproject.tool.api.ToolException; import org.sakaiproject.portal.util.URLUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; /** * Handler for managing the joining of a user to a site. @@ -47,8 +49,11 @@ public class JoinHandler extends BasePortalHandler private static final String URL_FRAGMENT = "join"; - public JoinHandler() - { + @Autowired private AuthzGroupService authzGroupService; + @Autowired private SiteService siteService; + + public JoinHandler() { + SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); setUrlFragment(URL_FRAGMENT); } @@ -98,7 +103,7 @@ protected void doJoin(String[] parts, HttpServletRequest req, if (site == null) { throw new IdUnusedException(siteId); } - SiteService.getInstance().join(site.getId()); + siteService.join(site.getId()); sendToSite(res, site); } else { // The user didn't opt to join @@ -145,7 +150,7 @@ protected void showJoin(String[] parts, HttpServletRequest req, throw new IdUnusedException(siteId); } // Check that the current user can access the site before we redirect. - if (site.getUserRole(session.getUserId()) != null && SiteService.allowAccessSite(site.getId())) + if (site.getUserRole(session.getUserId()) != null && siteService.allowAccessSite(site.getId())) { sendToSite(res, site); return; @@ -156,7 +161,7 @@ protected void showJoin(String[] parts, HttpServletRequest req, String serviceName = ServerConfigurationService.getString("ui.service", "Sakai"); // SAK-29138 - List siteProviders = (List) PortalSiteHelperImpl.getProviderIDsForSite(site); + List siteProviders = (List) authzGroupService.getProviderIds(site.getReference()); String title = serviceName + " : " + portal.getSiteHelper().getUserSpecificSiteTitle(site, true, false, siteProviders); String skin = site.getSkin(); @@ -164,7 +169,7 @@ protected void showJoin(String[] parts, HttpServletRequest req, context.put("currentSite", portal.getSiteHelper().convertSiteToMap(req, site, null, site.getId(), null, false, false, false, false, null, true, siteProviders)); context.put("uiService", serviceName); - boolean restrictedByAccountType = !SiteService.getInstance().isAllowedToJoin(site.getId()); + boolean restrictedByAccountType = !siteService.isAllowedToJoin(site.getId()); context.put("restrictedByAccountType", restrictedByAccountType); portal.sendResponse(context, res, "join", "text/html"); diff --git a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/PageHandler.java b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/PageHandler.java index 2abf2772b3f2..9f9df212ac35 100644 --- a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/PageHandler.java +++ b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/PageHandler.java @@ -38,7 +38,6 @@ import org.apache.commons.lang3.StringUtils; import org.sakaiproject.authz.api.SecurityService; -import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.PermissionException; @@ -54,6 +53,8 @@ import org.sakaiproject.tool.api.Session; import org.sakaiproject.tool.api.ToolException; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; /** * @author ieb @@ -67,11 +68,10 @@ public class PageHandler extends BasePortalHandler private static final String URL_FRAGMENT = "page"; - private SecurityService securityService = null; + @Autowired private SecurityService securityService = null; - public PageHandler() - { - securityService = (SecurityService) ComponentManager.get("org.sakaiproject.authz.api.SecurityService"); + public PageHandler() { + SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); setUrlFragment(PageHandler.URL_FRAGMENT); } diff --git a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/RoleSwitchOutHandler.java b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/RoleSwitchOutHandler.java index f31756cd9668..be5c83ee9d35 100644 --- a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/RoleSwitchOutHandler.java +++ b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/RoleSwitchOutHandler.java @@ -19,7 +19,6 @@ import javax.servlet.http.HttpServletResponse; import org.sakaiproject.authz.api.SecurityService; -import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.event.api.EventTrackingService; import org.sakaiproject.event.api.NotificationService; @@ -31,21 +30,20 @@ import org.sakaiproject.site.api.SiteService; import org.sakaiproject.tool.api.Session; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; @Slf4j public class RoleSwitchOutHandler extends BasePortalHandler { private static final String URL_FRAGMENT = "role-switch-out"; - final EventTrackingService eventTrackingService; - final SecurityService securityService; - final SiteService siteService; + @Autowired private EventTrackingService eventTrackingService; + @Autowired private SecurityService securityService; + @Autowired private SiteService siteService; - public RoleSwitchOutHandler() - { - eventTrackingService = ComponentManager.get(EventTrackingService.class); - securityService = ComponentManager.get(SecurityService.class); - siteService = ComponentManager.get(SiteService.class); + public RoleSwitchOutHandler() { + SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); setUrlFragment(RoleSwitchOutHandler.URL_FRAGMENT); } diff --git a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/SiteHandler.java b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/SiteHandler.java index fd921abffa0a..dedcbf11ef30 100644 --- a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/SiteHandler.java +++ b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/SiteHandler.java @@ -33,13 +33,13 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; +import org.sakaiproject.authz.api.AuthzGroupService; import org.sakaiproject.authz.api.Role; import org.sakaiproject.authz.api.SecurityService; import org.sakaiproject.component.api.ServerConfigurationService; @@ -59,7 +59,6 @@ import org.sakaiproject.portal.api.SiteView; import org.sakaiproject.portal.api.StoredState; import org.sakaiproject.portal.charon.site.AllSitesViewImpl; -import org.sakaiproject.portal.charon.site.PortalSiteHelperImpl; import org.sakaiproject.portal.util.ByteArrayServletResponse; import org.sakaiproject.portal.util.ToolUtils; import org.sakaiproject.portal.util.URLUtils; @@ -135,8 +134,8 @@ public class SiteHandler extends WorksiteHandler { private static final String SAK_PROP_SHOW_SITE_LABELS = "portal.siteList.siteLabels"; private static final boolean SAK_PROP_SHOW_SITE_LABELS_DFLT = true; + @Autowired private AuthzGroupService authzGroupService; @Autowired private CourseManagementService courseManagementService; - @Autowired private ActiveToolManager toolManager; @Autowired private EventTrackingService eventTrackingService; @Autowired private PreferencesService preferencesService; @Autowired private PresenceService presenceService; @@ -146,9 +145,9 @@ public class SiteHandler extends WorksiteHandler { @Autowired private SessionManager sessionManager; @Autowired private SiteService siteService; @Autowired private ThreadLocalManager threadLocalManager; + @Autowired private ActiveToolManager toolManager; @Autowired private UserDirectoryService userDirectoryService; - @Resource(name = "org.sakaiproject.time.api.UserTimeService") - private UserTimeService userTimeService; + @Autowired private UserTimeService userTimeService; // When these strings appear in the URL they will be replaced by a calculated value based on the context. // This can be replaced by the users myworkspace. @@ -424,7 +423,7 @@ public void doSite(HttpServletRequest req, HttpServletResponse res, Session sess session.removeAttribute(Portal.ATTR_SITE_PAGE + siteId); // SAK-29138 - form a context sensitive title - List providers = PortalSiteHelperImpl.getProviderIDsForSites(List.of(site)).get(site.getReference()); + List providers = new ArrayList<>(authzGroupService.getProviderIds(site.getReference())); String title = serverConfigurationService.getString("ui.service","Sakai") + " : " + portal.getSiteHelper().getUserSpecificSiteTitle(site, false, false, providers); diff --git a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/TimeoutDialogHandler.java b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/TimeoutDialogHandler.java index f1a9c36118c2..3b6e9ac73886 100644 --- a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/TimeoutDialogHandler.java +++ b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/TimeoutDialogHandler.java @@ -30,7 +30,8 @@ import org.sakaiproject.portal.api.PortalRenderContext; import org.sakaiproject.tool.api.Session; import org.sakaiproject.component.api.ServerConfigurationService; -import org.sakaiproject.component.cover.ComponentManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; /** * This is a portal handler to get the necessary information for the timeout @@ -64,15 +65,13 @@ public class TimeoutDialogHandler extends BasePortalHandler private static final String URL_FRAGMENT = "timeout"; private static final String CONFIG_PART = "config"; - private ServerConfigurationService serverConfigService; + @Autowired private ServerConfigurationService serverConfigService; - public TimeoutDialogHandler() - { + public TimeoutDialogHandler() { + SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); setUrlFragment(TimeoutDialogHandler.URL_FRAGMENT); - serverConfigService = (ServerConfigurationService) - ComponentManager.get(ServerConfigurationService.class); } - + @Override public int doGet(String[] parts, HttpServletRequest req, HttpServletResponse res, Session session) diff --git a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/AbstractSiteViewImpl.java b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/AbstractSiteViewImpl.java index ba20cb6a526e..91b42520fca6 100644 --- a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/AbstractSiteViewImpl.java +++ b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/AbstractSiteViewImpl.java @@ -28,149 +28,59 @@ import javax.servlet.http.HttpServletRequest; +import lombok.Setter; import org.sakaiproject.component.api.ServerConfigurationService; import org.sakaiproject.portal.api.SiteNeighbourhoodService; import org.sakaiproject.portal.api.SiteView; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SiteService; import org.sakaiproject.tool.api.Session; -import org.sakaiproject.user.api.PreferencesService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; -/** - * @author ieb - */ -public abstract class AbstractSiteViewImpl implements SiteView -{ +public abstract class AbstractSiteViewImpl implements SiteView { - protected PortalSiteHelperImpl siteHelper; + @Autowired protected ServerConfigurationService serverConfigurationService; + @Autowired protected SiteNeighbourhoodService siteNeighbourhoodService; + @Setter protected String prefix; + @Setter protected String toolContextPath; + @Setter protected boolean doPages = false; + @Setter protected boolean expandSite = false; + @Setter protected boolean includeSummary = false; + @Setter protected boolean resetTools = false; + protected ArrayList moreSites; protected HttpServletRequest request; - - protected String currentSiteId; - - protected SiteService siteService; - - protected String prefix; - - protected String toolContextPath; - - protected ServerConfigurationService serverConfigurationService; - - protected Session session; - - protected PreferencesService preferencesService; - protected List mySites; - - protected ArrayList moreSites; - + protected Map renderContextMap; + protected PortalSiteHelperImpl siteHelper; + protected Session session; + protected SiteService siteService; + protected String currentSiteId; protected String myWorkspaceSiteId; - protected boolean loggedIn; - protected Map renderContextMap; - - protected boolean resetTools = false; - - protected boolean doPages = false; - - protected boolean includeSummary = false; - - protected boolean expandSite = false; + public AbstractSiteViewImpl() { + SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); + } - public AbstractSiteViewImpl(PortalSiteHelperImpl siteHelper, SiteNeighbourhoodService siteNeighbourhoodService, - HttpServletRequest request, Session session, String currentSiteId, SiteService siteService, - ServerConfigurationService serverConfigurationService, PreferencesService preferencesService) - { + public AbstractSiteViewImpl(PortalSiteHelperImpl siteHelper, HttpServletRequest request, Session session, String currentSiteId) { + this(); this.siteHelper = siteHelper; this.request = request; this.currentSiteId = currentSiteId; - this.siteService = siteService; this.session = session; - this.preferencesService = preferencesService; - this.serverConfigurationService = serverConfigurationService; - - - - boolean showMyWorkspace = serverConfigurationService.getBoolean("myworkspace.show",true); - mySites = siteNeighbourhoodService.getSitesAtNode(request, session, showMyWorkspace); - - + boolean showMyWorkspace = serverConfigurationService.getBoolean("myworkspace.show", true); + mySites = siteNeighbourhoodService.getSitesAtNode(request, session, showMyWorkspace); loggedIn = session.getUserId() != null; Site myWorkspaceSite = siteHelper.getMyWorkspace(session); - if (myWorkspaceSite != null) - { + if (myWorkspaceSite != null) { myWorkspaceSiteId = myWorkspaceSite.getId(); } - renderContextMap = new HashMap(); - + renderContextMap = new HashMap<>(); } - - /* - * (non-Javadoc) - * - * @see org.sakaiproject.portal.api.SiteView#isEmpty() - */ - public boolean isEmpty() - { + public boolean isEmpty() { return mySites.isEmpty(); } - - /* - * (non-Javadoc) - * - * @see org.sakaiproject.portal.api.SiteView#setPrefix(java.lang.String) - */ - public void setPrefix(String prefix) - { - this.prefix = prefix; - - } - - /* - * (non-Javadoc) - * - * @see org.sakaiproject.portal.api.SiteView#setToolContextPath(java.lang.String) - */ - public void setToolContextPath(String toolContextPath) - { - this.toolContextPath = toolContextPath; - - } - - /* (non-Javadoc) - * @see org.sakaiproject.portal.api.SiteView#setResetTools(boolean) - */ - public void setResetTools(boolean resetTools) - { - this.resetTools = resetTools; - - } - - /* (non-Javadoc) - * @see org.sakaiproject.portal.api.SiteView#setDoPages(boolean) - */ - public void setDoPages(boolean doPages) - { - this.doPages = doPages; - } - - /* (non-Javadoc) - * @see org.sakaiproject.portal.api.SiteView#setIncludeSummary(boolean) - */ - public void setIncludeSummary(boolean includeSummary) - { - this.includeSummary = includeSummary; - } - - /* (non-Javadoc) - * @see org.sakaiproject.portal.api.SiteView#setExpandSite(boolean) - */ - public void setExpandSite(boolean expandSite) - { - this.expandSite = expandSite; - } - - } diff --git a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/AllSitesViewImpl.java b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/AllSitesViewImpl.java index f1b9514511d0..bef4278f3965 100644 --- a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/AllSitesViewImpl.java +++ b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/AllSitesViewImpl.java @@ -21,36 +21,20 @@ package org.sakaiproject.portal.charon.site; -import javax.servlet.http.HttpServletRequest; - -import org.sakaiproject.component.api.ServerConfigurationService; -import org.sakaiproject.portal.api.SiteNeighbourhoodService; -import org.sakaiproject.site.api.SiteService; import org.sakaiproject.tool.api.Session; -import org.sakaiproject.user.api.PreferencesService; +import javax.servlet.http.HttpServletRequest; import java.util.List; -/** - * @author ieb - * - */ -public class AllSitesViewImpl extends AbstractSiteViewImpl -{ +public class AllSitesViewImpl extends AbstractSiteViewImpl { - public AllSitesViewImpl(PortalSiteHelperImpl siteHelper, SiteNeighbourhoodService siteNeighbourhoodService, - HttpServletRequest request, Session session, String currentSiteId, SiteService siteService, - ServerConfigurationService serverConfigurationService, PreferencesService preferencesService) - { - super(siteHelper, siteNeighbourhoodService, request, session, currentSiteId, siteService, - serverConfigurationService, preferencesService); + public AllSitesViewImpl(PortalSiteHelperImpl siteHelper, + HttpServletRequest request, Session session, String currentSiteId) { + super(siteHelper, request, session, currentSiteId); } - /* (non-Javadoc) - * @see org.sakaiproject.portal.api.SiteView#getRenderContextObject() - */ - public Object getRenderContextObject() - { + @Override + public Object getRenderContextObject() { List l = siteHelper.convertSitesToMaps(request, mySites, prefix, currentSiteId, myWorkspaceSiteId, includeSummary, expandSite, resetTools, doPages, toolContextPath, loggedIn); diff --git a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/CurrentSiteViewImpl.java b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/CurrentSiteViewImpl.java index 8b95433d85c8..7f9a4e110510 100644 --- a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/CurrentSiteViewImpl.java +++ b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/CurrentSiteViewImpl.java @@ -21,60 +21,48 @@ package org.sakaiproject.portal.charon.site; -import java.util.List; -import javax.servlet.http.HttpServletRequest; - -import org.sakaiproject.component.api.ServerConfigurationService; +import lombok.Setter; +import org.sakaiproject.authz.api.AuthzGroupService; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.portal.api.SiteView; -import org.sakaiproject.portal.api.SiteNeighbourhoodService; import org.sakaiproject.site.api.Site; -import org.sakaiproject.site.api.SiteService; import org.sakaiproject.tool.api.Session; -import org.sakaiproject.user.api.PreferencesService; - -/** - * @author ieb - */ -public class CurrentSiteViewImpl implements SiteView -{ - - protected PortalSiteHelperImpl siteHelper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; - protected HttpServletRequest request; - - protected String currentSiteId; +import javax.servlet.http.HttpServletRequest; +import java.util.ArrayList; +import java.util.List; - protected String prefix; +public class CurrentSiteViewImpl implements SiteView { - protected String toolContextPath; + @Autowired private AuthzGroupService authzGroupService; + private Object siteMap; + private boolean initDone; + protected HttpServletRequest request; + protected PortalSiteHelperImpl siteHelper; protected Session session; - + protected String currentSiteId; protected String myWorkspaceSiteId; - protected boolean loggedIn; - - protected boolean resetTools = false; - - private Object siteMap; - - private boolean initDone; - - private boolean includeSummary; - - private boolean doPages; - - private boolean expandSite; + @Setter private boolean doPages; + @Setter private boolean expandSite; + @Setter private boolean includeSummary; + @Setter protected String prefix; + @Setter protected String toolContextPath; + @Setter protected boolean resetTools = false; + + public CurrentSiteViewImpl() { + SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); + } public CurrentSiteViewImpl(PortalSiteHelperImpl siteHelper, - SiteNeighbourhoodService siteNeighbourhoodService, - HttpServletRequest request, Session session, String currentSiteId, - SiteService siteService, - ServerConfigurationService serverConfigurationService, - PreferencesService preferencesService) - { + HttpServletRequest request, + Session session, + String currentSiteId) { + this(); this.siteHelper = siteHelper; this.request = request; this.currentSiteId = currentSiteId; @@ -83,117 +71,35 @@ public CurrentSiteViewImpl(PortalSiteHelperImpl siteHelper, Site myWorkspaceSite = siteHelper.getMyWorkspace(session); loggedIn = session.getUserId() != null; - if (myWorkspaceSite != null) - { + if (myWorkspaceSite != null) { myWorkspaceSiteId = myWorkspaceSite.getId(); } initDone = false; } - private void init() - { + private void init() { if (initDone) return; - try - { + try { Site site = siteHelper.getSiteVisit(currentSiteId); - List siteProviders = (List) PortalSiteHelperImpl.getProviderIDsForSite(site); + List siteProviders = new ArrayList<>(authzGroupService.getProviderIds(site.getReference())); siteMap = siteHelper .convertSiteToMap(request, site, prefix, currentSiteId, myWorkspaceSiteId, includeSummary, /* expandSite */true, resetTools, doPages, toolContextPath, loggedIn, siteProviders); } - catch (IdUnusedException e) - { - siteMap = null; - } - catch (PermissionException e) - { + catch (IdUnusedException | PermissionException e) { siteMap = null; } - } + } - /* - * (non-Javadoc) - * - * @see org.sakaiproject.portal.api.SiteView#isEmpty() - */ - public boolean isEmpty() - { + public boolean isEmpty() { init(); return (siteMap == null); } - /* - * (non-Javadoc) - * - * @see org.sakaiproject.portal.api.SiteView#setPrefix(java.lang.String) - */ - public void setPrefix(String prefix) - { - this.prefix = prefix; - - } - - /* - * (non-Javadoc) - * - * @see org.sakaiproject.portal.api.SiteView#setToolContextPath(java.lang.String) - */ - public void setToolContextPath(String toolContextPath) - { - this.toolContextPath = toolContextPath; - - } - - /* - * (non-Javadoc) - * - * @see org.sakaiproject.portal.api.SiteView#setResetTools(boolean) - */ - public void setResetTools(boolean resetTools) - { - this.resetTools = resetTools; - - } - - /* - * (non-Javadoc) - * - * @see org.sakaiproject.portal.api.SiteView#getRenderContextObject() - */ - public Object getRenderContextObject() - { + public Object getRenderContextObject() { init(); return siteMap; } - - /* - * (non-Javadoc) - * - * @see org.sakaiproject.portal.api.SiteView#setDoPages(boolean) - */ - public void setDoPages(boolean doPages) - { - this.doPages = doPages; - } - - /* - * (non-Javadoc) - * - * @see org.sakaiproject.portal.api.SiteView#setIncludeSummary(boolean) - */ - public void setIncludeSummary(boolean includeSummary) - { - this.includeSummary = includeSummary; - - } - - /* (non-Javadoc) - * @see org.sakaiproject.portal.api.SiteView#setExpandSite(boolean) - */ - public void setExpandSite(boolean expandSite) - { - this.expandSite = expandSite; - } } diff --git a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/DefaultSiteViewImpl.java b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/DefaultSiteViewImpl.java index d85bac5a2b3b..b223169146ea 100644 --- a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/DefaultSiteViewImpl.java +++ b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/DefaultSiteViewImpl.java @@ -21,60 +21,29 @@ package org.sakaiproject.portal.charon.site; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Iterator; - -import javax.servlet.http.HttpServletRequest; - -import org.sakaiproject.component.api.ServerConfigurationService; -import org.sakaiproject.entity.api.ResourceProperties; +import lombok.extern.slf4j.Slf4j; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.portal.api.Portal; -import org.sakaiproject.portal.api.SiteNeighbourhoodService; import org.sakaiproject.site.api.Site; -import org.sakaiproject.site.api.SiteService; -import org.sakaiproject.site.api.ToolConfiguration; import org.sakaiproject.site.api.SitePage; +import org.sakaiproject.site.api.ToolConfiguration; import org.sakaiproject.tool.api.Session; -import org.sakaiproject.user.api.Preferences; -import org.sakaiproject.user.api.PreferencesService; - import org.sakaiproject.util.Web; -import lombok.extern.slf4j.Slf4j; -/** - * @author ieb - */ +import javax.servlet.http.HttpServletRequest; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + @Slf4j -public class DefaultSiteViewImpl extends AbstractSiteViewImpl -{ - /** - * @param siteHelper - * @param request - * @param session - * @param currentSiteId - * @param siteService - * @param serverConfigurationService - * @param preferencesService - */ - public DefaultSiteViewImpl(PortalSiteHelperImpl siteHelper, SiteNeighbourhoodService siteNeighbourhoodService, HttpServletRequest request, - Session session, String currentSiteId, SiteService siteService, - ServerConfigurationService serverConfigurationService, - PreferencesService preferencesService) - { - super(siteHelper, siteNeighbourhoodService, request, session, currentSiteId, siteService, - serverConfigurationService, preferencesService); +public class DefaultSiteViewImpl extends AbstractSiteViewImpl { + + public DefaultSiteViewImpl(PortalSiteHelperImpl siteHelper, HttpServletRequest request, Session session, String currentSiteId) { + super(siteHelper, request, session, currentSiteId); } - /* - * (non-Javadoc) - * - * @see org.sakaiproject.portal.api.SiteView#getRenderContextObject() - */ - public Object getRenderContextObject() - { + public Object getRenderContextObject() { // Get the list of sites in the right order, // My WorkSpace will be the first in the list @@ -82,7 +51,7 @@ public Object getRenderContextObject() boolean siteFound = false; for (int i = 0; i < mySites.size(); i++) { - if (((Site) mySites.get(i)).getId().equals(currentSiteId)) + if (mySites.get(i).getId().equals(currentSiteId)) { siteFound = true; } @@ -200,42 +169,16 @@ public Object getRenderContextObject() return renderContextMap; } - /** - */ - protected void processMySites() - { - } - - /* - * (non-Javadoc) - * - * @see org.sakaiproject.portal.api.SiteView#isEmpty() - */ - public boolean isEmpty() - { - return mySites.isEmpty(); + protected void processMySites() { } - /* - * (non-Javadoc) - * - * @see org.sakaiproject.portal.api.SiteView#setPrefix(java.lang.String) - */ - public void setPrefix(String prefix) - { + @Override + public void setPrefix(String prefix) { this.prefix = prefix; - } - /* - * (non-Javadoc) - * - * @see org.sakaiproject.portal.api.SiteView#setToolContextPath(java.lang.String) - */ - public void setToolContextPath(String toolContextPath) - { + @Override + public void setToolContextPath(String toolContextPath) { this.toolContextPath = toolContextPath; - } - } diff --git a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/MoreSiteViewImpl.java b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/MoreSiteViewImpl.java index b4f6ef640e68..4c0f7b91c4b6 100644 --- a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/MoreSiteViewImpl.java +++ b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/MoreSiteViewImpl.java @@ -51,41 +51,18 @@ import org.sakaiproject.util.Web; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; -/** - * @author ieb - */ @Slf4j -public class MoreSiteViewImpl extends AbstractSiteViewImpl -{ - /** messages. */ +public class MoreSiteViewImpl extends AbstractSiteViewImpl { private static ResourceLoader rb = new ResourceLoader("sitenav"); - /** - * @param siteHelper - * @param request - * @param session - * @param currentSiteId - * @param siteService - * @param serverConfigurationService - * @param preferencesService - */ - public MoreSiteViewImpl(PortalSiteHelperImpl siteHelper, SiteNeighbourhoodService siteNeighbourhoodService, HttpServletRequest request, - Session session, String currentSiteId, SiteService siteService, - ServerConfigurationService serverConfigurationService, - PreferencesService preferencesService) - { - super(siteHelper, siteNeighbourhoodService, request, session, currentSiteId, siteService, - serverConfigurationService, preferencesService); + public MoreSiteViewImpl(PortalSiteHelperImpl siteHelper, HttpServletRequest request, Session session, String currentSiteId) { + super(siteHelper, request, session, currentSiteId); } - /* - * (non-Javadoc) - * - * @see org.sakaiproject.portal.api.SiteView#getRenderContextObject() - */ - public Object getRenderContextObject() - { + public Object getRenderContextObject() { // Get the list of sites in the right order, // My WorkSpace will be the first in the list @@ -93,7 +70,7 @@ public Object getRenderContextObject() boolean siteFound = false; for (int i = 0; i < mySites.size(); i++) { - if (((Site) mySites.get(i)).getId().equals(currentSiteId)) + if (mySites.get(i).getId().equals(currentSiteId)) { siteFound = true; } @@ -118,7 +95,6 @@ public Object getRenderContextObject() String profileToolId = serverConfigurationService.getString("portal.profiletool","sakai.profile2"); String calendarToolId = serverConfigurationService.getString("portal.calendartool","sakai.schedule"); - String preferencesToolId = serverConfigurationService.getString("portal.preferencestool","sakai.preferences"); String worksiteToolId = serverConfigurationService.getString("portal.worksitetool","sakai.sitesetup"); String profileToolUrl = null; @@ -369,16 +345,16 @@ public int compare(Map first, Map second) } private static class SitePanesArrangement { - public Map sitesInLeftPane = new TreeMap(); - public Map sitesInRightPane = new TreeMap(); + public Map sitesInLeftPane = new TreeMap<>(); + public Map sitesInRightPane = new TreeMap<>(); } private SitePanesArrangement arrangeSitesIntoPanes(Map tabsMoreTerms) { SitePanesArrangement result = new SitePanesArrangement(); for (String term : tabsMoreTerms.keySet()) { - result.sitesInLeftPane.put(term, new ArrayList()); - result.sitesInRightPane.put(term, new ArrayList()); + result.sitesInLeftPane.put(term, new ArrayList<>()); + result.sitesInRightPane.put(term, new ArrayList<>()); for (Map site : (List)tabsMoreTerms.get(term)) { if (isCourseType((String)site.get("siteType"))) { @@ -393,63 +369,36 @@ private SitePanesArrangement arrangeSitesIntoPanes(Map tabsMoreTer } - /* - * (non-Javadoc) - * - * @see org.sakaiproject.portal.api.SiteView#isEmpty() - */ - public boolean isEmpty() - { - return mySites.isEmpty(); - } - - /* - * (non-Javadoc) - * - * @see org.sakaiproject.portal.api.SiteView#setPrefix(java.lang.String) - */ - public void setPrefix(String prefix) - { + @Override + public void setPrefix(String prefix) { this.prefix = prefix; - } - /* - * (non-Javadoc) - * - * @see org.sakaiproject.portal.api.SiteView#setToolContextPath(java.lang.String) - */ - public void setToolContextPath(String toolContextPath) - { + @Override + public void setToolContextPath(String toolContextPath) { this.toolContextPath = toolContextPath; - } /** * read the site Type definition from configuration files */ - public List getSiteTypeStrings(String type) - { + public List getSiteTypeStrings(String type) { String[] siteTypes = serverConfigurationService.getStrings(type + "SiteType"); - if (siteTypes == null || siteTypes.length == 0) - { + if (siteTypes == null || siteTypes.length == 0) { siteTypes = new String[] {type}; } return Arrays.asList(siteTypes); } - private boolean isCourseType(String type) - { + private boolean isCourseType(String type) { List courseSiteTypes = getSiteTypeStrings("course"); if (courseSiteTypes.contains(type)) return true; else return false; } - private boolean isProjectType(String type) - { + private boolean isProjectType(String type) { List projectSiteTypes = getSiteTypeStrings("project"); if (projectSiteTypes.contains(type)) return true; else return false; } - } diff --git a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/PortalSiteHelperImpl.java b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/PortalSiteHelperImpl.java index 8ff64be1fd8c..68c3fe5d5aa5 100644 --- a/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/PortalSiteHelperImpl.java +++ b/portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/PortalSiteHelperImpl.java @@ -62,7 +62,6 @@ import org.sakaiproject.alias.api.AliasService; import org.sakaiproject.authz.api.AuthzGroupService; import org.sakaiproject.authz.api.SecurityService; -import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.component.api.ServerConfigurationService; import org.sakaiproject.db.api.SqlService; import org.sakaiproject.entity.api.Entity; @@ -101,6 +100,8 @@ import org.sakaiproject.util.Web; import org.sakaiproject.util.api.FormattedText; import org.sakaiproject.util.comparator.AliasCreatedTimeComparator; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; import org.springframework.web.util.UriComponentsBuilder; import lombok.extern.slf4j.Slf4j; @@ -134,69 +135,28 @@ public class PortalSiteHelperImpl implements PortalSiteHelper private Portal portal; - private AliasService aliasService; - private EntityManager entityManager; - private PortalService portalService; - private PreferencesService preferencesService; - private SecurityService securityService; - private ServerConfigurationService serverConfigurationService; - private SessionManager sessionManager; - private SiteNeighbourhoodService siteNeighbourhoodService; - private SiteService siteService; - private SqlService sqlService; - private ThreadLocalManager threadLocalManager; - private UserDirectoryService userDirectoryService; + @Autowired private AliasService aliasService; + @Autowired private AuthzGroupService authzGroupService; + @Autowired private EntityManager entityManager; + @Autowired private FormattedText formattedText; + @Autowired private PortalService portalService; + @Autowired private PreferencesService preferencesService; + @Autowired private SecurityService securityService; + @Autowired private ServerConfigurationService serverConfigurationService; + @Autowired private SessionManager sessionManager; + @Autowired private SiteNeighbourhoodService siteNeighbourhoodService; + @Autowired private SiteService siteService; + @Autowired private SqlService sqlService; + @Autowired private ThreadLocalManager threadLocalManager; + @Autowired private ToolManager toolManager; + @Autowired private UserDirectoryService userDirectoryService; private boolean lookForPageAliases; - // 2.3 back port - // private final String PROP_PARENT_ID = "sakai:parent-id"; - - private ToolManager toolManager; - private FormattedText formattedText; - - public ToolManager getToolManager() { - //To work around injection for test case - if (toolManager==null) { - toolManager = (ToolManager) ComponentManager.get(ToolManager.class.getName()); - } - return toolManager; - } - - public FormattedText getFormattedText() { - if (formattedText == null) { - formattedText = ComponentManager.get(FormattedText.class); - } - return formattedText; - } - - private static AuthzGroupService getAuthzGroupService() { - return (AuthzGroupService) ComponentManager.get(AuthzGroupService.class.getName()); - } - - public void setToolManager(ToolManager toolManager) { - this.toolManager = toolManager; - } - - /** - * @param portal - */ - public PortalSiteHelperImpl(Portal portal, boolean lookForPageAliases) - { + public PortalSiteHelperImpl(Portal portal, boolean lookForPageAliases) { + SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); this.portal = portal; this.lookForPageAliases = lookForPageAliases; - aliasService = ComponentManager.get(AliasService.class); - entityManager = ComponentManager.get(EntityManager.class); - portalService = ComponentManager.get(PortalService.class); - siteService = ComponentManager.get(SiteService.class); - securityService = ComponentManager.get(SecurityService.class); - serverConfigurationService = ComponentManager.get(ServerConfigurationService.class); - preferencesService = ComponentManager.get(PreferencesService.class); - sessionManager = ComponentManager.get(SessionManager.class); - siteNeighbourhoodService = ComponentManager.get(SiteNeighbourhoodService.class); - sqlService = ComponentManager.get(SqlService.class); - threadLocalManager = ComponentManager.get(ThreadLocalManager.class); - userDirectoryService = ComponentManager.get(UserDirectoryService.class); } /* (non-Javadoc) @@ -506,7 +466,9 @@ public List convertSitesToMaps(HttpServletRequest req, List mySites, List pinned = portalService.getPinnedSites(); // Determine the depths of the child sites if needed - Map> realmProviderMap = getProviderIDsForSites(mySites); + List mySiteRefs = mySites.stream().map(Entity::getReference).collect(Collectors.toList()); + Map> realmProviderMap = authzGroupService.getProviderIDsForRealms(mySiteRefs); + for (Site s : mySites) { // The first site is the current site @@ -558,44 +520,6 @@ public List convertSitesToMaps(HttpServletRequest req, List mySites, return l; } - /** - * Get all provider IDs for the given site. - * - * @param site the site to retrieve all provider IDs - * @return a List of Strings of provider IDs for the given site - */ - public static List getProviderIDsForSite(Site site) - { - List providers = new ArrayList<>(); - if (site != null) - { - providers.addAll(getAuthzGroupService().getProviderIds(site.getReference())); - } - - return providers; - } - - /** - * Get all provider IDs for all sites given. - * - * @param sites the list of sites to retrieve all provider IDs - * @return a Map, where the key is the realm ID, and the value is a list of provider IDs for that site - */ - public static Map> getProviderIDsForSites(List sites) { - - if (sites.isEmpty()) { - return Collections.EMPTY_MAP; - } - - List realmIDs - = sites.stream().map(s -> s.getReference()).collect(Collectors.toList()); - - return getAuthzGroupService().getProviderIDsForRealms(realmIDs); - } - - /** - * {@inheritDoc} - */ public String getUserSpecificSiteTitle( Site site, boolean escaped ) { return getUserSpecificSiteTitle( site, true, escaped, null ); @@ -611,12 +535,12 @@ public String getUserSpecificSiteTitle(Site site, boolean truncated, boolean esc String retVal = siteService.getUserSpecificSiteTitle( site, userDirectoryService.getCurrentUser().getId(), siteProviders ); if( truncated ) { - retVal = getFormattedText().makeShortenedText( retVal, null, null, null ); + retVal = formattedText.makeShortenedText( retVal, null, null, null ); } if( escaped ) { - retVal = getFormattedText().escapeHtml( retVal ); + retVal = formattedText.escapeHtml( retVal ); } return retVal; @@ -650,8 +574,8 @@ public Map convertSiteToMap(HttpServletRequest req, Site s, Stri .equals(myWorkspaceSiteId)))); String siteTitleRaw = getUserSpecificSiteTitle(s, false, false, siteProviders); - String siteTitle = getFormattedText().escapeHtml(siteTitleRaw); - String siteTitleTruncated = getFormattedText().escapeHtml(getFormattedText().makeShortenedText(siteTitleRaw, null, null, null)); + String siteTitle = formattedText.escapeHtml(siteTitleRaw); + String siteTitleTruncated = formattedText.escapeHtml(formattedText.makeShortenedText(siteTitleRaw, null, null, null)); m.put("siteTitle", siteTitle); m.put("siteTitleTrunc", siteTitleTruncated); m.put("fullTitle", siteTitle); @@ -661,15 +585,15 @@ public Map convertSiteToMap(HttpServletRequest req, Site s, Stri if (s.getShortDescription() != null && s.getShortDescription().trim().length() > 0) { // SAK-23895: Allow display of site description in the tab instead of site title String shortDesc = s.getShortDescription(); - String shortDesc_trimmed = getFormattedText().makeShortenedText(shortDesc, null, null, null); - m.put("shortDescription", getFormattedText().escapeHtml(shortDesc_trimmed)); + String shortDesc_trimmed = formattedText.makeShortenedText(shortDesc, null, null, null); + m.put("shortDescription", formattedText.escapeHtml(shortDesc_trimmed)); } String siteUrl = RequestFilter.serverUrl(req) + serverConfigurationService.getString("portalPath") + "/"; if (prefix != null) siteUrl = siteUrl + prefix + "/"; // siteUrl = siteUrl + Web.escapeUrl(siteHelper.getSiteEffectiveId(s)); - m.put("siteUrl", siteUrl + getFormattedText().escapeUrl(getSiteEffectiveId(s))); + m.put("siteUrl", siteUrl + formattedText.escapeUrl(getSiteEffectiveId(s))); m.put("siteType", s.getType()); m.put("siteId", s.getId()); @@ -694,13 +618,13 @@ public Map convertSiteToMap(HttpServletRequest req, Site s, Stri Site site = pwd.get(i); log.debug("PWD[{}]={}{}", i, site.getId(), site.getTitle()); Map pm = new HashMap<>(); - List providers = getProviderIDsForSite(site); + List providers = new ArrayList<>(authzGroupService.getProviderIds(site.getReference())); String parentSiteTitle = getUserSpecificSiteTitle(site, false, false, providers); - String parentSiteTitleTruncated = getFormattedText().makeShortenedText(parentSiteTitle, null, null, null); + String parentSiteTitleTruncated = formattedText.makeShortenedText(parentSiteTitle, null, null, null); pm.put("siteTitle", parentSiteTitle); pm.put("siteTitleTrunc", parentSiteTitleTruncated); - pm.put("siteUrl", siteUrl + getFormattedText().escapeUrl(getSiteEffectiveId(site))); + pm.put("siteUrl", siteUrl + formattedText.escapeUrl(getSiteEffectiveId(site))); l.add(pm); isChild = true; @@ -932,10 +856,10 @@ else if ("always".equals(showHelpGlobal)) m.put("current", Boolean.valueOf(current)); m.put("ispopup", Boolean.valueOf(p.isPopUp())); m.put("pagePopupUrl", pagePopupUrl); - m.put("pageTitle", getFormattedText().escapeHtml(p.getTitle())); - m.put("jsPageTitle", getFormattedText().escapeJavascript(p.getTitle())); - m.put("pageId", getFormattedText().escapeUrl(p.getId())); - m.put("jsPageId", getFormattedText().escapeJavascript(p.getId())); + m.put("pageTitle", formattedText.escapeHtml(p.getTitle())); + m.put("jsPageTitle", formattedText.escapeJavascript(p.getTitle())); + m.put("pageId", formattedText.escapeUrl(p.getId())); + m.put("jsPageId", formattedText.escapeJavascript(p.getId())); m.put("pageRefUrl", pageRefUrl); m.put("pageResetUrl", pageResetUrl); m.put("toolpopup", Boolean.valueOf(source!=null)); @@ -977,7 +901,7 @@ else if ("always".equals(showHelpGlobal)) } String toolUrl = Web.returnUrl(req, "/" + portalPrefix + "/" - + getFormattedText().escapeUrl(getSiteEffectiveId(site))); + + formattedText.escapeUrl(getSiteEffectiveId(site))); if (resetTools) { toolUrl = toolUrl + "/tool-reset/"; } else { @@ -994,15 +918,15 @@ else if ("always".equals(showHelpGlobal)) Tool tool = placement.getTool(); if (tool != null) { - String toolrefUrl = toolUrl + getFormattedText().escapeUrl(placement.getId()); + String toolrefUrl = toolUrl + formattedText.escapeUrl(placement.getId()); Map m = new HashMap(); m.put("isPage", Boolean.valueOf(false)); - m.put("toolId", getFormattedText().escapeUrl(placement.getId())); - m.put("jsToolId", getFormattedText().escapeJavascript(placement.getId())); + m.put("toolId", formattedText.escapeUrl(placement.getId())); + m.put("jsToolId", formattedText.escapeJavascript(placement.getId())); m.put("toolRegistryId", placement.getToolId()); - m.put("toolTitle", getFormattedText().escapeHtml(placement.getTitle())); - m.put("jsToolTitle", getFormattedText().escapeJavascript(placement.getTitle())); + m.put("toolTitle", formattedText.escapeHtml(placement.getTitle())); + m.put("jsToolTitle", formattedText.escapeJavascript(placement.getTitle())); m.put("toolrefUrl", toolrefUrl); m.put("toolpopup", Boolean.valueOf(source!=null)); m.put("toolpopupurl", source); @@ -1083,7 +1007,7 @@ else if ("always".equals(showHelpGlobal)) } String presenceUrl - = Web.returnUrl(req, "/presence/" + getFormattedText().escapeUrl(site.getId())); + = Web.returnUrl(req, "/presence/" + formattedText.escapeUrl(site.getId())); theMap.put("pageNavShowPresenceLoggedIn", Boolean.valueOf(showPresence && loggedIn)); @@ -1162,7 +1086,7 @@ public boolean setTemporaryPlacement(Site site) { if (site == null) return false; - Placement ppp = getToolManager().getCurrentPlacement(); + Placement ppp = toolManager.getCurrentPlacement(); if (ppp != null && site.getId().equals(ppp.getContext())) { return true; @@ -1176,7 +1100,7 @@ public boolean setTemporaryPlacement(Site site) threadLocalManager.set(CURRENT_PLACEMENT, placement); // Debugging - ppp = getToolManager().getCurrentPlacement(); + ppp = toolManager.getCurrentPlacement(); if (ppp == null) { log.warn("portal-temporary placement not set - null"); @@ -1533,7 +1457,7 @@ private String buildAlias(String alias, Site site) public boolean allowTool(Site site, Placement placement) { - return getToolManager().allowTool(site, placement); + return toolManager.allowTool(site, placement); } /** @@ -1542,7 +1466,7 @@ public boolean allowTool(Site site, Placement placement) */ public boolean isHidden(Placement placement) { - return getToolManager().isHidden(placement); + return toolManager.isHidden(placement); } /* * (non-Javadoc) @@ -1557,11 +1481,11 @@ public SiteView getSitesView(View view, HttpServletRequest request, Session sess switch (view) { case CURRENT_SITE_VIEW: - return new CurrentSiteViewImpl(this, portal.getSiteNeighbourhoodService(), request, session, siteId, siteService, serverConfigurationService, preferencesService); + return new CurrentSiteViewImpl(this, request, session, siteId); case ALL_SITES_VIEW: - return new AllSitesViewImpl(this, portal.getSiteNeighbourhoodService(), request, session, siteId, siteService, serverConfigurationService, preferencesService); + return new AllSitesViewImpl(this, request, session, siteId); case DHTML_MORE_VIEW: - return new MoreSiteViewImpl(this,portal.getSiteNeighbourhoodService(), request, session, siteId, siteService, serverConfigurationService, preferencesService); + return new MoreSiteViewImpl(this, request, session, siteId); } return null; } diff --git a/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/PortalTestConfiguration.java b/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/PortalTestConfiguration.java index 4a97d3c886fa..e408144034c2 100644 --- a/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/PortalTestConfiguration.java +++ b/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/PortalTestConfiguration.java @@ -1,6 +1,7 @@ package org.sakaiproject.portal.charon; import org.mockito.Mockito; +import org.sakaiproject.authz.api.AuthzGroupService; import org.sakaiproject.authz.api.SecurityService; import org.sakaiproject.component.api.ServerConfigurationService; import org.sakaiproject.coursemanagement.api.CourseManagementService; @@ -9,7 +10,6 @@ import org.sakaiproject.profile2.logic.ProfileImageLogic; import org.sakaiproject.site.api.SiteService; import org.sakaiproject.thread_local.api.ThreadLocalManager; -import org.sakaiproject.time.api.TimeService; import org.sakaiproject.time.api.UserTimeService; import org.sakaiproject.tool.api.ActiveToolManager; import org.sakaiproject.tool.api.SessionManager; @@ -28,6 +28,11 @@ public ActiveToolManager activeToolManager() { return mock(ActiveToolManager.class); } + @Bean(name = "org.sakaiproject.authz.api.AuthzGroupService") + public AuthzGroupService authzGroupService() { + return mock(AuthzGroupService.class); + } + @Bean(name = "org.sakaiproject.coursemanagement.api.CourseManagementService") public CourseManagementService courseManagementService() { return mock(CourseManagementService.class); @@ -81,11 +86,11 @@ public ThreadLocalManager threadLocalManager() { return mock(ThreadLocalManager.class); } - @Bean(name = "org.sakaiproject.time.api.TimeService") - public TimeService timeService() { - return mock(TimeService.class); - } - +// @Bean(name = "org.sakaiproject.time.api.TimeService") +// public TimeService timeService() { +// return mock(TimeService.class); +// } +// @Bean(name = "org.sakaiproject.user.api.UserDirectoryService") public UserDirectoryService userDirectoryService() { return mock(UserDirectoryService.class); diff --git a/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/handlers/SiteHandlerTest.java b/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/handlers/SiteHandlerTest.java index 56a87cadcbc7..7a6f089357d7 100644 --- a/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/handlers/SiteHandlerTest.java +++ b/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/handlers/SiteHandlerTest.java @@ -19,11 +19,8 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.portal.charon.PortalTestConfiguration; -import org.sakaiproject.time.api.TimeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.AbstractApplicationContext; @@ -37,7 +34,6 @@ import java.util.Collections; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockStatic; import static org.sakaiproject.portal.charon.handlers.SiteHandler.PageParts; @RunWith(SpringJUnit4ClassRunner.class) @@ -47,7 +43,6 @@ public class SiteHandlerTest { public static boolean setupOnceCompleted = false; @Autowired private ApplicationContext applicationContext; - @Autowired private TimeService timeService; private SiteHandler siteHandler; @@ -68,10 +63,7 @@ public void setUp() { setupOnceCompleted = true; } - try (MockedStatic cm = mockStatic(ComponentManager.class)) { - cm.when(() -> ComponentManager.get(TimeService.class)).thenReturn(timeService); - siteHandler = new SiteHandler(); - } + this.siteHandler = new SiteHandler(); } @Test diff --git a/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/handlers/StaticHandlerTest.java b/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/handlers/StaticHandlerTest.java index 9835d321f81e..16eb7ddc60f9 100644 --- a/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/handlers/StaticHandlerTest.java +++ b/portal/portal-impl/impl/src/test/java/org/sakaiproject/portal/charon/handlers/StaticHandlerTest.java @@ -21,47 +21,72 @@ package org.sakaiproject.portal.charon.handlers; -import java.io.File; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.sakaiproject.portal.api.PortalHandlerException; +import org.sakaiproject.portal.charon.PortalTestConfiguration; +import org.sakaiproject.tool.api.Session; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.AbstractApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.context.ContextLoader; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.support.GenericWebApplicationContext; +import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.util.Collections; -import junit.framework.TestCase; +import static org.mockito.Mockito.mock; -import org.sakaiproject.component.cover.ComponentManager; -import org.sakaiproject.portal.api.PortalHandlerException; -import org.sakaiproject.tool.api.Session; +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {PortalTestConfiguration.class}) +public class StaticHandlerTest { -public class StaticHandlerTest extends TestCase { + public static boolean setupOnceCompleted = false; - public void testGetContentType() { - StaticHandler handler = new StaticHandler() { - + @Autowired private ApplicationContext applicationContext; + + private StaticHandler staticHandler; + + @Before + public void setUp() { + if (!setupOnceCompleted) { + // Setup a fake webapp so spring injection will happen + ServletContext servletContext = mock(ServletContext.class); + Mockito.when(servletContext.getInitParameterNames()).thenReturn(Collections.emptyEnumeration()); + Mockito.when(servletContext.getAttributeNames()).thenReturn(Collections.emptyEnumeration()); + + WebApplicationContext webApplicationContext = new GenericWebApplicationContext(servletContext); + ((AbstractApplicationContext) webApplicationContext).setParent(applicationContext); + ContextLoader contextLoader = new ContextLoader(webApplicationContext); + contextLoader.initWebApplicationContext(servletContext); + + setupOnceCompleted = true; + } + + this.staticHandler = new StaticHandler() { @Override - public int doGet(String[] parts, HttpServletRequest req, - HttpServletResponse res, Session session) - throws PortalHandlerException { - // TODO Auto-generated method stub + public int doGet(String[] parts, HttpServletRequest req, HttpServletResponse res, Session session) throws PortalHandlerException { return 0; } }; - // Check we get this correct. - assertEquals("text/javascript", handler.getContentType(new File("myfile.js").getName())); - assertEquals("text/javascript", handler.getContentType(new File("/somepath/to/myfile.js").getName())); - assertEquals("text/javascript", handler.getContentType(new File("another/path/myfile.js").getName())); - // Check trailing don't don't break things. - assertEquals("application/octet-stream", handler.getContentType(new File("file.that.ends.with.dot.").getName())); } - @Override - protected void setUp() throws Exception { - super.setUp(); - ComponentManager.testingMode = true; - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - ComponentManager.shutdown(); + @Test + public void testGetContentType() { + // Check we get this correct. + Assert.assertEquals("text/javascript", staticHandler.getContentType(new File("myfile.js").getName())); + Assert.assertEquals("text/javascript", staticHandler.getContentType(new File("/somepath/to/myfile.js").getName())); + Assert.assertEquals("text/javascript", staticHandler.getContentType(new File("another/path/myfile.js").getName())); + // Check trailing don't don't break things. + Assert.assertEquals("application/octet-stream", staticHandler.getContentType(new File("file.that.ends.with.dot.").getName())); } }