public static org.sakaiproject.site.api.Site getSite(java.lang.String param0) throws org.sakaiproject.exception.IdUnusedException { org.sakaiproject.site.api.SiteService service = getInstance(); if (service == null) return null; return service.getSite(param0); }
/** get announcement group information */ private String getAnnouncementGroup(AnnouncementMessage a) { if (a.getProperties().getProperty(ResourceProperties.PROP_PUBVIEW) != null && a.getProperties() .getProperty(ResourceProperties.PROP_PUBVIEW) .equals(Boolean.TRUE.toString())) { return rb.getString("Public"); } else if (a.getAnnouncementHeader().getAccess().equals(MessageHeader.MessageAccess.CHANNEL)) { return rb.getString("Allgroups"); } else { int count = 0; String allGroupString = ""; try { Site site = siteService.getSite(entityManager.newReference(a.getReference()).getContext()); for (Iterator i = a.getAnnouncementHeader().getGroups().iterator(); i.hasNext(); ) { Group aGroup = site.getGroup((String) i.next()); if (aGroup != null) { count++; if (count > 1) { allGroupString = allGroupString.concat(", ").concat(aGroup.getTitle()); } else { allGroupString = aGroup.getTitle(); } } } } catch (IdUnusedException e) { // No site available. } return allGroupString; } }
@Override protected String plainTextContent(Event event) { StringBuilder buf = new StringBuilder(); String newline = "\n\r"; // get the message Reference ref = entityManager.newReference(event.getResource()); AnnouncementMessage msg = (AnnouncementMessage) ref.getEntity(); AnnouncementMessageHeader hdr = (AnnouncementMessageHeader) msg.getAnnouncementHeader(); // use either the configured site, or if not configured, the site (context) of the resource String siteId = (getSite() != null) ? getSite() : ref.getContext(); String url = ServerConfigurationService.getPortalUrl() + "/site/" + siteId; // get a site title String title = siteId; try { Site site = siteService.getSite(siteId); title = site.getTitle(); } catch (Exception ignore) { } // Now build up the message text. if (AnnouncementService.SECURE_ANNC_ADD.equals(event.getEvent())) { buf.append( FormattedText.convertFormattedTextToPlaintext( rb.getFormattedMessage("noti.header.add", new Object[] {title, url}))); } else { buf.append( FormattedText.convertFormattedTextToPlaintext( rb.getFormattedMessage("noti.header.update", new Object[] {title, url}))); } buf.append(" " + rb.getString("at_date") + " "); buf.append(hdr.getDate().toStringLocalFull()); buf.append(newline); buf.append(FormattedText.convertFormattedTextToPlaintext(msg.getBody())); buf.append(newline); // add any attachments List attachments = hdr.getAttachments(); if (attachments.size() > 0) { buf.append(newline + rb.getString("Attachments") + newline); for (Iterator iAttachments = attachments.iterator(); iAttachments.hasNext(); ) { Reference attachment = (Reference) iAttachments.next(); String attachmentTitle = attachment.getProperties().getPropertyFormatted(ResourceProperties.PROP_DISPLAY_NAME); buf.append(attachmentTitle + ": " + attachment.getUrl() + newline); } } return buf.toString(); }
private Course getCourse(final String siteContext) { if (log.isDebugEnabled()) log.debug("Getting course for context " + siteContext); Site site; try { site = siteService.getSite(siteContext); } catch (IdUnusedException e) { log.error("Could not find site with id = " + siteContext); return null; } return new CourseImpl(site); }
/** @inheritDoc */ public List getSections(final String siteContext) { if (log.isDebugEnabled()) log.debug("Getting sections for context " + siteContext); List<CourseSectionImpl> sectionList = new ArrayList<CourseSectionImpl>(); Collection<Group> sections; try { sections = siteService.getSite(siteContext).getGroups(); } catch (IdUnusedException e) { log.error("No site with id = " + siteContext); return sectionList; } for (Iterator<Group> iter = sections.iterator(); iter.hasNext(); ) { Group group = (Group) iter.next(); sectionList.add(new CourseSectionImpl(group)); } Collections.sort(sectionList); return sectionList; }
/** @inheritDoc */ public List getSectionsInCategory(final String siteContext, final String categoryId) { if (log.isDebugEnabled()) log.debug("Getting " + categoryId + " sections for context " + siteContext); List<CourseSection> sectionList = new ArrayList<CourseSection>(); Collection groups; try { groups = siteService.getSite(siteContext).getGroups(); } catch (IdUnusedException e) { log.error("No site with id = " + siteContext); return new ArrayList(); } for (Iterator iter = groups.iterator(); iter.hasNext(); ) { Group group = (Group) iter.next(); if (categoryId.equals(group.getProperties().getProperty(CourseSectionImpl.CATEGORY))) { sectionList.add(new CourseSectionImpl(group)); } } return sectionList; }
/** * Format the announcement notification subject line. * * @param event The event that matched criteria to cause the notification. * @return the announcement notification subject line. */ protected String getSubject(Event event) { // get the message Reference ref = entityManager.newReference(event.getResource()); AnnouncementMessage msg = (AnnouncementMessage) ref.getEntity(); AnnouncementMessageHeader hdr = (AnnouncementMessageHeader) msg.getAnnouncementHeader(); // use either the configured site, or if not configured, the site (context) of the resource String siteId = (getSite() != null) ? getSite() : ref.getContext(); // get a site title String title = siteId; try { Site site = siteService.getSite(siteId); title = site.getTitle(); } catch (Exception ignore) { } // use the message's subject return rb.getFormattedMessage("noti.subj", new Object[] {title, hdr.getSubject()}); }
/** build the context for batch archive confirm */ public String buildDownloadContext( VelocityPortlet portlet, Context context, RunData rundata, SessionState state) { context.put("tlang", rb); buildMenu(context); // get list of existing archives Collection<File> files = Collections.<File>emptySet(); File archiveBaseDir = new File(serverConfigurationService.getString("archive.storage.path", "sakai/archive")); if (archiveBaseDir.exists() && archiveBaseDir.isDirectory()) { files = FileUtils.listFiles(archiveBaseDir, new SuffixFileFilter(".zip"), null); } List<SparseFile> zips = new ArrayList<SparseFile>(); SimpleDateFormat dateFormatIn = new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat dateFormatOut = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar calendar = Calendar.getInstance(); // porcess the list. also get the hash for the file if it exists for (File f : files) { String absolutePath = f.getAbsolutePath(); SparseFile sf = new SparseFile(); sf.setFilename(f.getName()); sf.setAbsolutePath(absolutePath); sf.setSize(FileUtils.byteCountToDisplaySize(f.length())); // get the datetime string, its the last part of the file name, convert back to a date that we // can display String dateTimeStr = StringUtils.substringAfterLast(StringUtils.removeEnd(f.getName(), ".zip"), "-"); try { Date date = dateFormatIn.parse(dateTimeStr); sf.setDateCreated(dateFormatOut.format(date)); } catch (ParseException pe) { // ignore, just don't set the date } // get siteId, first part of name String siteId = StringUtils.substringBeforeLast(f.getName(), "-"); sf.setSiteId(siteId); // try to get site title if the site still exists try { Site site = siteService.getSite(siteId); sf.setSiteTitle(site.getTitle()); } catch (IdUnusedException e) { // ignore, no site available } // get the hash. need to read it from the file. Same filename but diff extension String hashFilePath = StringUtils.removeEnd(absolutePath, ".zip"); hashFilePath = hashFilePath + ".sha1"; File hashFile = new File(hashFilePath); try { String hash = FileUtils.readFileToString(hashFile); sf.setHash(hash); } catch (IOException e) { // ignore, dont use the hash } zips.add(sf); } context.put("archives", zips); return "-download"; }
private void generateReportTable(List<Stat> data, ReportParams params) throws SAXException { if (data == null || params == null) { throw new NullPointerException("Parameter 'data', 'params' must not be null"); } if (handler == null) { throw new IllegalStateException("ContentHandler not set"); } final Map<String, ToolInfo> eventIdToolMap = M_ers.getEventIdToolMap(); boolean showSite = M_rm.isReportColumnAvailable(params, StatsManager.T_SITE); boolean showUser = M_rm.isReportColumnAvailable(params, StatsManager.T_USER); boolean showTool = M_rm.isReportColumnAvailable(params, StatsManager.T_TOOL); boolean showEvent = M_rm.isReportColumnAvailable(params, StatsManager.T_EVENT); boolean showResource = M_rm.isReportColumnAvailable(params, StatsManager.T_RESOURCE); boolean showResourceAction = M_rm.isReportColumnAvailable(params, StatsManager.T_RESOURCE_ACTION); boolean showDate = M_rm.isReportColumnAvailable(params, StatsManager.T_DATE) || M_rm.isReportColumnAvailable(params, StatsManager.T_DATEMONTH) || M_rm.isReportColumnAvailable(params, StatsManager.T_DATEYEAR); boolean showLastDate = M_rm.isReportColumnAvailable(params, StatsManager.T_LASTDATE); boolean showTotal = M_rm.isReportColumnAvailable(params, StatsManager.T_TOTAL); boolean showTotalVisits = M_rm.isReportColumnAvailable(params, StatsManager.T_VISITS); boolean showTotalUnique = M_rm.isReportColumnAvailable(params, StatsManager.T_UNIQUEVISITS); boolean showDuration = M_rm.isReportColumnAvailable(params, StatsManager.T_DURATION); Iterator<Stat> i = data.iterator(); while (i.hasNext()) { Stat cs = i.next(); handler.startElement("datarow"); // set column display info setColumnDisplayInfo(params); if (showSite) { String siteId = cs.getSiteId(); String site = null; try { site = M_ss.getSite(siteId).getTitle(); } catch (IdUnusedException e) { site = msgs.getString("site_unknown"); } handler.element("site", site); } if (showUser) { String userId = null; String userName = null; String id = cs.getUserId(); if (id != null) { if (("-").equals(id)) { userId = "-"; userName = msgs.getString("user_anonymous"); } else if (("?").equals(id)) { userId = "-"; userName = msgs.getString("user_anonymous_access"); } else { try { User user = M_uds.getUser(id); userId = user.getDisplayId(); userName = M_sm.getUserNameForDisplay(user); } catch (UserNotDefinedException e1) { userId = id; userName = msgs.getString("user_unknown"); } } } else { userName = msgs.getString("user_unknown"); } handler.element("userid", userId); handler.element("username", userName); } if (showTool) { EventStat es = (EventStat) cs; String toolId = es.getToolId(); handler.element("tool", M_ers.getToolName(toolId == null ? "" : toolId)); handler.element("showToolIcon", "true"); handler.element("toolicon", "sitestats://" + M_ers.getToolIcon(toolId)); } if (showEvent) { EventStat es = (EventStat) cs; String eventRef = es.getEventId(); handler.element("event", M_ers.getEventName(eventRef == null ? "" : eventRef)); ToolInfo toolInfo = eventIdToolMap.get(eventRef); if (toolInfo != null && !showTool) { handler.element("showToolEventIcon", "true"); String toolId = toolInfo.getToolId(); handler.element("tooleventicon", "sitestats://" + M_ers.getToolIcon(toolId)); } else { handler.element("showToolEventIcon", "false"); } } if (showResource) { ResourceStat rs = (ResourceStat) cs; String resName = M_sm.getResourceName(rs.getResourceRef()); handler.element("resource", resName == null ? "" : resName); handler.element( "resourceimg", "library://" + M_sm.getResourceImageLibraryRelativePath(rs.getResourceRef())); } if (showResourceAction) { ResourceStat rs = (ResourceStat) cs; String resAction = rs.getResourceAction(); handler.element("action", resAction == null ? "" : msgs.getString("action_" + resAction)); } if (showDate) { java.util.Date date = cs.getDate(); if (M_rm.isReportColumnAvailable(params, StatsManager.T_DATE)) { handler.element( "date", date == null ? "" : M_ts.newTime(date.getTime()).toStringLocalDate()); } else if (M_rm.isReportColumnAvailable(params, StatsManager.T_DATEMONTH)) { handler.element("date", date == null ? "" : dateMonthFrmt.format(date)); } else if (M_rm.isReportColumnAvailable(params, StatsManager.T_DATEYEAR)) { handler.element("date", date == null ? "" : dateYearFrmt.format(date)); } } if (showLastDate) { java.util.Date date = cs.getDate(); handler.element( "lastdate", date == null ? "" : M_ts.newTime(date.getTime()).toStringLocalDate()); } if (showTotal) { handler.element("total", String.valueOf(cs.getCount())); } if (showTotalVisits) { SiteVisits ss = (SiteVisits) cs; handler.element("totalVisits", String.valueOf(ss.getTotalVisits())); } if (showTotalUnique) { SiteVisits ss = (SiteVisits) cs; handler.element("totalUnique", String.valueOf(ss.getTotalUnique())); } if (showDuration) { SitePresence ss = (SitePresence) cs; double durationInMin = ss.getDuration() == 0 ? 0 : Util.round((double) ss.getDuration() / 1000 / 60, 1); // in minutes handler.element("duration", String.valueOf(durationInMin)); } handler.endElement("datarow"); } // empty report if (data.size() == 0) { String messageNoData = msgs.getString("no_data"); handler.startElement("datarow"); // set column display info setColumnDisplayInfo(params); if (showSite) { handler.element("site", messageNoData); messageNoData = ""; } if (showUser) { handler.element("userid", messageNoData); messageNoData = ""; handler.element("username", messageNoData); } if (showTool) { handler.element("tool", messageNoData); messageNoData = ""; handler.element("showToolIcon", ""); handler.element("toolicon", ""); } if (showEvent) { handler.element("event", messageNoData); messageNoData = ""; handler.element("showToolEventIcon", "false"); } if (showResource) { handler.element("resource", messageNoData); messageNoData = ""; handler.element("resourceimg", ""); } if (showResourceAction) { handler.element("action", messageNoData); messageNoData = ""; } if (showDate) { handler.element("date", messageNoData); messageNoData = ""; } if (showLastDate) { handler.element("lastdate", messageNoData); messageNoData = ""; } if (showTotal) { handler.element("total", messageNoData); messageNoData = ""; } if (showTotalVisits) { handler.element("totalVisits", messageNoData); messageNoData = ""; } if (showTotalUnique) { handler.element("totalUnique", messageNoData); messageNoData = ""; } if (showDuration) { handler.element("duration", messageNoData); messageNoData = ""; } handler.endElement("datarow"); } }
/** * Format the announcement notification from address. * * @param event The event that matched criteria to cause the notification. * @return the announcement notification from address. */ protected String getFromAddress(Event event) { Reference ref = entityManager.newReference(event.getResource()); // SAK-14831, yorkadam, make site title reflected in 'From:' name instead of default // ServerConfigurationService.getString("ui.service", "Sakai"); String siteId = (getSite() != null) ? getSite() : ref.getContext(); String title = ""; try { Site site = siteService.getSite(siteId); title = site.getTitle(); } catch (Exception ignore) { } String userEmail = ServerConfigurationService.getString( "setup.request", "no-reply@" + ServerConfigurationService.getServerName()); String userDisplay = ServerConfigurationService.getString("ui.service", "Sakai"); // String no_reply = "From: \"" + userDisplay + "\" <" + userEmail + ">"; // String no_reply_withTitle = "From: \"" + title + "\" <" + userEmail + ">"; String from = "From: Sakai"; // fallback value if (title != null && !title.equals("")) { from = "From: \"" + title + "\" <" + userEmail + ">"; } else { String fromVal = getFrom(event); // should not return null but better safe than sorry if (fromVal != null) { from = fromVal; } } // get the message AnnouncementMessage msg = (AnnouncementMessage) ref.getEntity(); String userId = msg.getAnnouncementHeader().getFrom().getId(); // checks if "from" email id has to be included? and whether the notification is a delayed // notification?. SAK-13512 // SAK-20988 - emailFromReplyable@org.sakaiproject.event.api.NotificationService is deprecated boolean notificationEmailFromReplyable = ServerConfigurationService.getBoolean("notify.email.from.replyable", false); if (notificationEmailFromReplyable && from.contains("no-reply@") && userId != null) { try { User u = userDirectoryService.getUser(userId); userDisplay = u.getDisplayName(); userEmail = u.getEmail(); if ((userEmail != null) && (userEmail.trim().length()) == 0) userEmail = null; } catch (UserNotDefinedException e) { M_log.warn( "Failed to load user from announcement header: " + userId + ". Will send from no-reply@" + ServerConfigurationService.getServerName() + " instead."); } // some fallback positions if (userEmail == null) userEmail = ServerConfigurationService.getString( "setup.request", "no-reply@" + ServerConfigurationService.getServerName()); if (userDisplay == null) userDisplay = ServerConfigurationService.getString("ui.service", "Sakai"); from = "From: \"" + userDisplay + "\" <" + userEmail + ">"; } return from; }
// run this before each test starts protected void onSetUpBeforeTransaction() throws Exception { // Time /*long oneMonthAgoMs = new Date().getTime() - (30 * 24 * 60 * 60 * 1000); long twoMonthAgoMs = new Date().getTime() - (2 * 30 * 24 * 60 * 60 * 1000); Time timeA = createMock(Time.class); expect(timeA.getTime()).andReturn(oneMonthAgoMs).anyTimes(); replay(timeA); Time timeB = createMock(Time.class); expect(timeB.getTime()).andReturn(twoMonthAgoMs).anyTimes(); replay(timeB);*/ // Site Service M_ss = createMock(SiteService.class); // null site expect(M_ss.getSite(null)).andThrow(new IdUnusedException("null")).anyTimes(); expect(M_ss.getSite("non_existent_site")) .andThrow(new IdUnusedException("non_existent_site")) .anyTimes(); // My Workspace - user sites FakeSite userSiteA = new FakeSite("~" + FakeData.USER_A_ID); FakeSite userSiteB = new FakeSite("~" + FakeData.USER_B_ID); expect(M_ss.getSiteUserId(FakeData.USER_A_ID)).andStubReturn("~" + FakeData.USER_A_ID); expect(M_ss.getSiteUserId(FakeData.USER_B_ID)).andStubReturn("~" + FakeData.USER_B_ID); expect(M_ss.getSiteUserId("no_user")).andStubReturn(null); expect(M_ss.getSite("~" + FakeData.USER_A_ID)).andStubReturn(userSiteA); expect(M_ss.getSite("~" + FakeData.USER_B_ID)).andStubReturn(userSiteB); // Site A has tools {SiteStats, Chat, Resources}, has {user-a,user-b}, created 1 month ago Site siteA = new FakeSite( FakeData.SITE_A_ID, Arrays.asList( StatsManager.SITESTATS_TOOLID, FakeData.TOOL_CHAT, StatsManager.RESOURCES_TOOLID)); ((FakeSite) siteA) .setUsers(new HashSet<String>(Arrays.asList(FakeData.USER_A_ID, FakeData.USER_B_ID))); ((FakeSite) siteA) .setMembers(new HashSet<String>(Arrays.asList(FakeData.USER_A_ID, FakeData.USER_B_ID))); expect(M_ss.getSite(FakeData.SITE_A_ID)).andStubReturn(siteA); expect(M_ss.isUserSite(FakeData.SITE_A_ID)).andStubReturn(false); expect(M_ss.isSpecialSite(FakeData.SITE_A_ID)).andStubReturn(false); // Site B has tools {TOOL_CHAT}, has {user-a}, created 2 months ago FakeSite siteB = new FakeSite(FakeData.SITE_B_ID, FakeData.TOOL_CHAT); ((FakeSite) siteB).setUsers(new HashSet<String>(Arrays.asList(FakeData.USER_A_ID))); ((FakeSite) siteB).setMembers(new HashSet<String>(Arrays.asList(FakeData.USER_A_ID))); expect(M_ss.getSite(FakeData.SITE_B_ID)).andStubReturn(siteB); expect(M_ss.isUserSite(FakeData.SITE_B_ID)).andStubReturn(false); expect(M_ss.isSpecialSite(FakeData.SITE_B_ID)).andStubReturn(false); // Site 'non_existent_site' doesn't exist expect(M_ss.isUserSite("non_existent_site")).andStubReturn(false); expect(M_ss.isSpecialSite("non_existent_site")).andStubReturn(false); // Content Hosting Service // M_chs = createMock(ContentHostingService.class); // M_chs.checkCollection("/group/site-a-id/folder/"); // expectLastCall().anyTimes(); // M_chs.checkResource("/group-user/site-a-id/user-a/resource1"); // expectLastCall().anyTimes(); ResourceLoader msgs = createMock(ResourceLoader.class); expect(msgs.getString((String) anyObject())) .andStubAnswer( new IAnswer<String>() { public String answer() throws Throwable { return (String) getCurrentArguments()[0]; } }); // apply replay(M_ss); // replay(M_chs); replay(msgs); ((FakeEventRegistryService) M_ers).setSiteService(M_ss); ((FakeEventRegistryService) M_ers).setToolManager(M_tm); ((FakeEventRegistryService) M_ers).setStatsManager(M_sm); ((ReportManagerImpl) M_rm).setEventRegistryService(M_ers); ((StatsManagerImpl) M_sm).setSiteService(M_ss); // ((StatsManagerImpl)M_sm).setContentHostingService(M_chs); ((StatsManagerImpl) M_sm).setResourceLoader(msgs); ((StatsManagerImpl) M_sm).setEnableSitePresences(true); ((ReportManagerImpl) M_rm).setResourceLoader(msgs); ((StatsUpdateManagerImpl) M_sum).setSiteService(M_ss); ((StatsUpdateManagerImpl) M_sum).setStatsManager(M_sm); }