/** * Format the to site email address. * * @param event The event that matched criteria to cause the notification. * @return the email address attribution for the site. */ protected String getToSite(Event event) { Reference ref = EntityManager.newReference(event.getResource()); // 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; String email = null; try { Site site = SiteService.getSite(siteId); title = site.getTitle(); // check that the channel exists String channel = "/mailarchive/channel/" + siteId + "/main"; EntityManager.newReference(channel); // find the alias for this site's mail channel List<Alias> all = AliasService.getAliases(channel); if (!all.isEmpty()) email = ((Alias) all.get(0)).getId(); } catch (Exception ignore) { } // if for any reason we did not find an email, setup for the no-reply for email if (email == null) email = "no-reply"; String rv = "\"" + title + "\" <" + email + "@" + ServerConfigurationService.getServerName() + ">"; return rv; }
/** * @throws SDataException * @throws RepositoryException */ public CHSNodeMap(ContentEntity n, int depth, ResourceDefinition rp) throws SDataException { String lock = ContentHostingService.AUTH_RESOURCE_HIDDEN; sessionManager = Kernel.sessionManager(); entityManager = Kernel.entityManager(); String userId = sessionManager.getCurrentSessionUserId(); String reference = n.getReference(); Reference referenceObj = entityManager.newReference(reference); Collection<?> groups = referenceObj.getAuthzGroups(); boolean canSeeHidden = Kernel.securityService().unlock(userId, lock, reference, groups); if (!canSeeHidden && !n.isAvailable()) { throw new SDataAccessException(403, "Permission denied on item"); } contentHostingService = Kernel.contentHostingService(); authZGroupService = Kernel.authzGroupService(); depth--; put("mixinNodeType", getMixinTypes(n)); put("properties", getProperties(n)); put("name", getName(n)); if (rp != null) { put("path", rp.getExternalPath(n.getId())); } put("permissions", getPermissions(n)); if (n instanceof ContentResource) { put("primaryNodeType", "nt:file"); addFile((ContentResource) n); } else { put("primaryNodeType", "nt:folder"); addFolder((ContentCollection) n, rp, depth); } }
/** * Do the getSiteVisit, but if not found and the id is a user site, try translating from user EID * to ID. * * @param siteId The Site Id. * @return The Site. * @throws PermissionException If not allowed. * @throws IdUnusedException If not found. */ public Site getSiteVisit(String siteId) throws PermissionException, IdUnusedException { try { return SiteService.getSiteVisit(siteId); } catch (IdUnusedException e) { if (SiteService.isUserSite(siteId)) { try { String userEid = SiteService.getSiteUserId(siteId); String userId = UserDirectoryService.getUserId(userEid); String alternateSiteId = SiteService.getUserSiteId(userId); return SiteService.getSiteVisit(alternateSiteId); } catch (UserNotDefinedException ee) { } } else { String reference = portal.getSiteNeighbourhoodService().parseSiteAlias(siteId); Reference ref = EntityManager.getInstance().newReference(reference); try { return SiteService.getSiteVisit(ref.getId()); } catch (IdUnusedException iue) { } } // re-throw if that didn't work throw e; } }
/** * Parse and load selected XML data file * * @return String that is used to determine the place where control is to be sent in * ControlImportProducer (reportNavigationCases method) * @throws SecurityException */ public String process() throws SecurityException { ToolSession toolSession = sessionManager.getCurrentToolSession(); List refs = null; String id = null; if (toolSession.getAttribute(FilePickerHelper.FILE_PICKER_CANCEL) == null && toolSession.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS) != null) { refs = (List) toolSession.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS); if (refs == null || refs.size() != 1) { return "no-reference"; } Reference ref = (Reference) refs.get(0); id = ref.getId(); } try { contentHostingService.checkResource(id); } catch (PermissionException e) { return "permission-exception"; } catch (IdUnusedException e) { return "idunused-exception"; } catch (TypeException e) { return "type-exception"; } try { evalImportLogic.load(id); } catch (Exception e) { return "exception"; } toolSession.removeAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS); toolSession.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL); return "importing"; }
private Map<String, String> getPermissions(ContentEntity n) throws SDataException { Map<String, String> map = new HashMap<String, String>(); if (n instanceof ContentCollection) { map.put("read", String.valueOf(contentHostingService.allowGetCollection(n.getId()))); map.put("remove", String.valueOf(contentHostingService.allowRemoveCollection(n.getId()))); map.put("write", String.valueOf(contentHostingService.allowUpdateCollection(n.getId()))); String ref = n.getReference(); Reference reference = entityManager.newReference(n.getReference()); if (log.isDebugEnabled()) { log.debug("Got Reference " + reference + " for " + n.getReference()); } Collection<?> groups = reference.getAuthzGroups(); String user = sessionManager.getCurrentSessionUserId(); map.put( "admin", String.valueOf( authZGroupService.isAllowed( sessionManager.getCurrentSessionUserId(), AuthzGroupService.SECURE_UPDATE_AUTHZ_GROUP, groups))); } else { map.put("read", String.valueOf(contentHostingService.allowGetResource(n.getId()))); map.put("remove", String.valueOf(contentHostingService.allowRemoveResource(n.getId()))); map.put("write", String.valueOf(contentHostingService.allowUpdateResource(n.getId()))); } return map; }
/** {@inheritDoc} */ public void save(AuthzGroup azGroup) throws GroupNotDefinedException, AuthzPermissionException { if (azGroup.getId() == null) throw new GroupNotDefinedException("<null>"); Reference ref = entityManager().newReference(azGroup.getId()); if (!SiteService.allowUpdateSiteMembership(ref.getId())) { // check security (throws if not permitted) unlock(SECURE_UPDATE_AUTHZ_GROUP, authzGroupReference(azGroup.getId())); } // make sure it's in storage if (!m_storage.check(azGroup.getId())) { // if this was new, create it in storage if (((BaseAuthzGroup) azGroup).m_isNew) { // reserve an AuthzGroup with this id from the info store - if it's in use, this will return // null AuthzGroup newAzg = m_storage.put(azGroup.getId()); if (newAzg == null) { M_log.warn("saveUsingSecurity, storage.put for a new returns null"); } } else { throw new GroupNotDefinedException(azGroup.getId()); } } // complete the save completeSave(azGroup); }
/** * Implementation of command pattern. Will be called by ScheduledInvocationManager for delayed * announcement notifications * * @param opaqueContext reference (context) for message */ public void execute(String opaqueContext) { // get the message final Reference ref = entityManager.newReference(opaqueContext); // needed to access the message enableSecurityAdvisorToGetAnnouncement(); final AnnouncementMessage msg = (AnnouncementMessage) ref.getEntity(); final AnnouncementMessageHeader hdr = (AnnouncementMessageHeader) msg.getAnnouncementHeader(); // read the notification options final String notification = msg.getProperties().getProperty("notificationLevel"); int noti = NotificationService.NOTI_OPTIONAL; if ("r".equals(notification)) { noti = NotificationService.NOTI_REQUIRED; } else if ("n".equals(notification)) { noti = NotificationService.NOTI_NONE; } final Event delayedNotificationEvent = eventTrackingService.newEvent("annc.schInv.notify", msg.getReference(), true, noti); // eventTrackingService.post(event); NotificationEdit notify = notificationService.addTransientNotification(); super.notify(notify, delayedNotificationEvent); // since we build the notification by accessing the // message within the super class, can't remove the // SecurityAdvisor until this point // done with access, need to remove from stack disableSecurityAdvisor(); }
@WebMethod @Path("/getSubmissionsForAssignment") @Produces("text/plain") @GET public String getSubmissionsForAssignment( @WebParam(name = "sessionId", partName = "sessionId") @QueryParam("sessionId") String sessionId, @WebParam(name = "assignmentId", partName = "assignmentId") @QueryParam("assignmentId") String assignmentId) { try { Session s = establishSession(sessionId); Assignment assign = assignmentService.getAssignment(assignmentId); List subs = assignmentService.getSubmissions(assign); // build the xml LOG.debug("about to start building xml doc"); Document dom = Xml.createDocument(); Node all = dom.createElement("submissions"); dom.appendChild(all); for (int i = 0; i < subs.size(); i++) { AssignmentSubmission thisSub = (AssignmentSubmission) subs.get(i); LOG.debug("got submission" + thisSub); Element uElement = dom.createElement("submission"); uElement.setAttribute("feedback-comment", thisSub.getFeedbackComment()); uElement.setAttribute("feedback-text", thisSub.getFeedbackText()); uElement.setAttribute("grade", thisSub.getGrade()); uElement.setAttribute("status", thisSub.getStatus()); uElement.setAttribute("submitted-text", thisSub.getSubmittedText()); List submitters = thisSub.getSubmitterIds(); for (int q = 0; q < submitters.size(); q++) { uElement.setAttribute("submitter-id", (String) submitters.get(q)); } List submissions = thisSub.getSubmittedAttachments(); // Element attachments = dom.createElement("attachment"); for (int q = 0; q < submissions.size(); q++) { // Element attachments = dom.createElement("attachment"); Reference ref = (Reference) submissions.get(q); Entity ent = ref.getEntity(); uElement.setAttribute("attachment-url", ent.getUrl()); // all.appendChild(); } all.appendChild(uElement); } String retVal = Xml.writeDocumentToString(dom); return retVal; } catch (Exception e) { LOG.error( "WS getSubmissionsForAssignment(): " + e.getClass().getName() + " : " + e.getMessage()); } return "<submissions />"; }
/** * 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 = "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().getDisplayId(); // 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) { } // some fallback positions if (userEmail == null) userEmail = "no-reply@" + ServerConfigurationService.getServerName(); if (userDisplay == null) userDisplay = ServerConfigurationService.getString("ui.service", "Sakai"); from = "From: \"" + userDisplay + "\" <" + userEmail + ">"; } return from; }
/** * Update the site security when an AuthzGroup is deleted, if it is a site AuthzGroup. * * @param azGroup The AuthzGroup. */ protected void removeSiteSecurity(AuthzGroup azGroup) { // Special code for the site service Reference ref = entityManager().newReference(azGroup.getId()); if (SiteService.APPLICATION_ID.equals(ref.getType()) && SiteService.SITE_SUBTYPE.equals(ref.getSubType())) { // no azGroup, no users Set empty = new HashSet(); SiteService.setSiteSecurity(ref.getId(), empty, empty, empty); } }
/** * Update the site security based on the values in the AuthzGroup, if it is a site AuthzGroup. * * @param azGroup The AuthzGroup. */ protected void updateSiteSecurity(AuthzGroup azGroup) { // Special code for the site service Reference ref = entityManager().newReference(azGroup.getId()); if (SiteService.APPLICATION_ID.equals(ref.getType()) && SiteService.SITE_SUBTYPE.equals(ref.getSubType())) { // collect the users Set updUsers = azGroup.getUsersIsAllowed(SiteService.SECURE_UPDATE_SITE); Set unpUsers = azGroup.getUsersIsAllowed(SiteService.SITE_VISIT_UNPUBLISHED); Set visitUsers = azGroup.getUsersIsAllowed(SiteService.SITE_VISIT); SiteService.setSiteSecurity(ref.getId(), updUsers, unpUsers, visitUsers); } }
/** If the url is a valid reference, convert it to a URL, else return it unchanged. */ protected String convertReferenceUrl(String url) { // make a reference Reference ref = EntityManager.newReference(url); // if it didn't recognize this, return it unchanged if (ref.isKnownType()) { // return the reference's url String refUrl = ref.getUrl(); if (refUrl != null) { return refUrl; } } return url; }
/** {@inheritDoc} */ public boolean parseEntityReference(String reference, Reference ref) { if (reference.startsWith(REFERENCE_ROOT)) { // /syllabus/siteid/syllabusid String[] parts = split(reference, Entity.SEPARATOR); String subType = null; String context = null; String id = null; String container = null; // the first part will be null, then next the service, the third will be "calendar" or "event" if (parts.length > 2) { // the site/context context = parts[2]; // the id if (parts.length > 3) { id = parts[3]; } } ref.set(APPLICATION_ID, subType, id, container, context); return true; } return false; }
/** @inheritDoc */ public void notify(Notification notification, Event event) { // get the message Reference ref = EntityManager.newReference(event.getResource()); AnnouncementMessageEdit msg = (AnnouncementMessageEdit) ref.getEntity(); AnnouncementMessageHeader hdr = (AnnouncementMessageHeader) msg.getAnnouncementHeader(); // do not do notification for hidden (draft) messages if (hdr.getDraft()) return; // Put here since if release date after now, do not notify // since scheduled notification has been set. Time now = TimeService.newTime(); if (now.after(hdr.getDate())) { super.notify(notification, event); } }
private List prepareItemAttachment(ItemDataIfc item, boolean isEditPendingAssessmentFlow) { ToolSession session = SessionManager.getCurrentToolSession(); if (session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS) != null) { Set attachmentSet = new HashSet(); if (item != null) { attachmentSet = item.getItemAttachmentSet(); } HashMap map = getResourceIdHash(attachmentSet); ArrayList newAttachmentList = new ArrayList(); AssessmentService assessmentService = new AssessmentService(); String protocol = ContextUtil.getProtocol(); List refs = (List) session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS); if (refs != null && refs.size() > 0) { Reference ref; for (int i = 0; i < refs.size(); i++) { ref = (Reference) refs.get(i); String resourceId = ref.getId(); if (map.get(resourceId) == null) { // new attachment, add log.debug("**** ref.Id=" + ref.getId()); log.debug( "**** ref.name=" + ref.getProperties() .getProperty(ref.getProperties().getNamePropDisplayName())); ItemAttachmentIfc newAttach = assessmentService.createItemAttachment( item, ref.getId(), ref.getProperties().getProperty(ref.getProperties().getNamePropDisplayName()), protocol, isEditPendingAssessmentFlow); newAttachmentList.add(newAttach); } else { // attachment already exist, let's add it to new list and // check it off from map newAttachmentList.add((ItemAttachmentIfc) map.get(resourceId)); map.remove(resourceId); } } } session.removeAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS); session.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL); return newAttachmentList; } else if (item == null) { return new ArrayList(); } else return item.getItemAttachmentList(); }
public ContentResource wrap(final ContentResource content) { if (!isFiltered(content)) { return content; } Reference contentRef = entityManager.newReference(content.getReference()); Reference siteRef = entityManager.newReference(contentRef.getContext()); Entity entity = siteRef.getEntity(); String addHtml = content.getProperties().getProperty(ResourceProperties.PROP_ADD_HTML); String skinRepo = getSkinRepo(); String siteSkin = getSiteSkin(entity); final boolean detectHtml = addHtml == null || addHtml.equals("auto"); String title = getTitle(content); final String header = MessageFormat.format(headerTemplate, skinRepo, siteSkin, title); final String footer = footerTemplate; return new WrappedContentResource(content, header, footer, detectHtml); }
/** * 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()}); }
/** * Format a to address, to the related site, but with no reply. * * @param event The event that matched criteria to cause the notification. * @return a to address, to the related site, but with no reply. */ protected String getToSiteNoReply(Event event) { Reference ref = EntityManager.newReference(event.getResource()); // 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) { } return "\"" + title + "\" <" + ServerConfigurationService.getString( "setup.request", "no-reply@" + ServerConfigurationService.getServerName()) + ">"; }
/** {@inheritDoc} */ public Collection getEntityAuthzGroups(Reference ref, String userId) { // permission convert Collection rv = new Vector(); try { // for 2.3 // Site site = SiteService.getSite(ref.getContext()); // Collection groups = site.getGroups(); // // if ((SecurityService.isSuperUser())) // { // return groups; // } // // Collection groupRefs = new Vector(); // for (Iterator i = groups.iterator(); i.hasNext();) // { // Group group = (Group) i.next(); // groupRefs.add(group.getReference()); // } // // for (Iterator i = groups.iterator(); i.hasNext();) // { // Group group = (Group) i.next(); // rv.add(group); // } // // ref.addSiteContextAuthzGroup(rv); if (SYLLABUS.equals(ref.getSubType())) { rv.add(ref.getReference()); ref.addSiteContextAuthzGroup(rv); } } catch (Exception e) { logger.error("SyllabusServiceImpl:getEntityAuthzGroups - " + e); e.printStackTrace(); } return rv; }
/** @inheritDoc */ public boolean checkReference(String ref) { // the rules: // Null is rejected // all blank is rejected // INVALID_CHARS_IN_RESOURCE_ID characters are rejected Reference r = newReference(ref); // just check the id... %%% need more? -ggolden String id = r.getId(); if (id == null) return false; if (id.trim().length() == 0) return false; // we must reject certain characters that we cannot even escape and get // into Tomcat via a URL for (int i = 0; i < id.length(); i++) { if (Validator.INVALID_CHARS_IN_RESOURCE_ID.indexOf(id.charAt(i)) != -1) return false; } return true; }
/** {@inheritDoc} */ public boolean parseEntityReference(String reference, Reference ref) { // for azGroup access if (reference.startsWith(REFERENCE_ROOT)) { // the azGroup id may have separators - we use everything after "/realm/" String id = reference.substring(REFERENCE_ROOT.length() + 1, reference.length()); ref.set(APPLICATION_ID, null, id, null, null); return true; } return false; }
/** @inheritDoc */ protected List<User> getRecipients(Event event) { // get the resource reference Reference ref = EntityManager.newReference(event.getResource()); // use either the configured site, or if not configured, the site (context) of the resource String siteId = (getSite() != null) ? getSite() : ref.getContext(); // if the site is published, use the list of users who can SITE_VISIT the site, // else use the list of users who can SITE_VISIT_UNP the site. try { Site site = SiteService.getSite(siteId); String ability = SiteService.SITE_VISIT; if (!site.isPublished()) { ability = SiteService.SITE_VISIT_UNPUBLISHED; } // get the list of users who can do the right kind of visit List<User> users = SecurityService.unlockUsers(ability, ref.getReference()); // get the list of users who have the appropriate access to the resource if (getResourceAbility() != null) { List<User> users2 = SecurityService.unlockUsers(getResourceAbility(), ref.getReference()); // find intersection of users and user2 users.retainAll(users2); } // only use direct site members for the base list of users refineToSiteMembers(users, site); // add any other users addSpecialRecipients(users, ref); return users; } catch (Exception any) { return new Vector<User>(); } }
@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(); }
/** {@inheritDoc} */ public Collection getEntityAuthzGroups(Reference ref, String userId) { // double check that it's mine if (APPLICATION_ID != ref.getType()) return null; Collection rv = new Vector(); // if the reference is an AuthzGroup, and not a special one // get the list of realms for the azGroup-referenced resource if ((ref.getId() != null) && (ref.getId().length() > 0) && (!ref.getId().startsWith("!"))) { // add the current user's azGroup (for what azGroup stuff everyone can do, i.e. add) ref.addUserAuthzGroup(rv, sessionManager().getCurrentSessionUserId()); // make a new reference on the azGroup's id Reference refnew = entityManager().newReference(ref.getId()); rv.addAll(refnew.getAuthzGroups(userId)); } return rv; }
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ReferenceHolder)) { return false; } final ReferenceHolder referenceHolder = (ReferenceHolder) o; if (base != null ? !base.getReference().equals(referenceHolder.base.getReference()) : referenceHolder.base != null) { return false; } return true; }
/** @inheritDoc */ protected String htmlContent(Event event) { StringBuilder buf = new StringBuilder(); String newline = "<br />\n"; // 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; String url = ServerConfigurationService.getPortalUrl() + "/site/" + siteId; try { Site site = SiteService.getSite(siteId); title = site.getTitle(); url = site.getUrl(); // Might have a better URL. } catch (Exception ignore) { M_log.warn("Failed to load site: " + siteId + " for: " + event.getResource()); } // Now build up the message text. if (AnnouncementService.SECURE_ANNC_ADD.equals(event.getEvent())) { buf.append(rb.getFormattedMessage("noti.header.add", new Object[] {title, url})); } else { buf.append(rb.getFormattedMessage("noti.header.update", new Object[] {title, url})); } buf.append(" " + rb.getString("at_date") + " "); buf.append(hdr.getDate().toStringLocalFull()); buf.append(newline); // add any attachments List<Reference> attachments = hdr.getAttachments(); if (attachments.size() > 0) { buf.append(newline + rb.getString("Attachments") + newline); for (Iterator<Reference> iAttachments = attachments.iterator(); iAttachments.hasNext(); ) { Reference attachment = (Reference) iAttachments.next(); String attachmentTitle = attachment.getProperties().getPropertyFormatted(ResourceProperties.PROP_DISPLAY_NAME); buf.append("<a href=\"" + attachment.getUrl() + "\">"); buf.append(attachmentTitle); buf.append("</a>" + newline); } } return buf.toString(); }
public String processCreate() { try { if (!this.checkAccess()) { throw new PermissionException( SessionManager.getCurrentSessionUserId(), "syllabus_access_athz", ""); } } catch (PermissionException e) { // logger.info(this + ".getEntries() in PostemTool " + e); FacesContext.getCurrentInstance() .addMessage( null, MessageUtils.getMessage( FacesMessage.SEVERITY_ERROR, "error_permission", (new Object[] {e.toString()}), FacesContext.getCurrentInstance())); this.currentGradebook = null; this.csv = null; this.newTemplate = null; // this.release = null; return "permission_error"; } if (currentGradebook.getId() == null) { ArrayList gb = getGradebooks(); Iterator gi = gb.iterator(); while (gi.hasNext()) { if (((Gradebook) gi.next()).getTitle().equals(currentGradebook.getTitle())) { // To stay consistent, remove current messages when adding a new message // so as to only display one error message before returning PostemTool.clearMessages(); PostemTool.populateMessage( FacesMessage.SEVERITY_ERROR, "duplicate_title", new Object[] {}); return "create_gradebook"; } } } if (currentGradebook.getTitle() == null || currentGradebook.getTitle().equals("")) { // To stay consistent, remove current messages when adding a new message // so as to only display one error message before returning PostemTool.clearMessages(); PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, "missing_title", new Object[] {}); return "create_gradebook"; } else if (currentGradebook.getTitle().trim().length() > TITLE_MAX_LENGTH) { PostemTool.clearMessages(); PostemTool.populateMessage( FacesMessage.SEVERITY_ERROR, "title_too_long", new Object[] { new Integer(currentGradebook.getTitle().trim().length()), new Integer(TITLE_MAX_LENGTH) }); return "create_gradebook"; } Reference attachment = getAttachmentReference(); if (attachment == null) { return "create_gradebook"; } if (!this.delimiter.equals(COMMA_DELIM_STR) && !this.delimiter.equals(TAB_DELIM_STR)) { PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, "invalid_delim", new Object[] {}); return "create_gradebook"; } if (attachment != null) { // logger.info("*** Non-Empty CSV!"); try { char csv_delim = CSV.COMMA_DELIM; if (this.delimiter.equals(TAB_DELIM_STR)) { csv_delim = CSV.TAB_DELIM; } // Read the data ContentResource cr = contentHostingService.getResource(attachment.getId()); // Check the type if (ResourceProperties.TYPE_URL.equalsIgnoreCase(cr.getContentType())) { // Going to need to read from a stream String csvURL = new String(cr.getContent()); // Load the URL csv = URLConnectionReader.getText(csvURL); if (LOG.isDebugEnabled()) { LOG.debug(csv); } } else { csv = new String(cr.getContent()); if (LOG.isDebugEnabled()) { LOG.debug(csv); } } CSV grades = new CSV(csv, withHeader, csv_delim); if (withHeader == true) { if (grades.getHeaders() != null) { List headingList = grades.getHeaders(); for (int col = 0; col < headingList.size(); col++) { String heading = (String) headingList.get(col).toString().trim(); // Make sure there are no blank headings if (heading == null || heading.equals("")) { PostemTool.populateMessage( FacesMessage.SEVERITY_ERROR, "blank_headings", new Object[] {}); return "create_gradebook"; } // Make sure the headings don't exceed max limit if (heading.length() > HEADING_MAX_LENGTH) { PostemTool.populateMessage( FacesMessage.SEVERITY_ERROR, "heading_too_long", new Object[] {new Integer(HEADING_MAX_LENGTH)}); return "create_gradebook"; } } } } if (grades.getStudents() != null) { if (!usernamesValid(grades)) { return "create_gradebook"; } if (hasADuplicateUsername(grades)) { return "create_gradebook"; } } if (this.newTemplate != null && this.newTemplate.trim().length() > 0) { if (this.newTemplate.trim().length() > TEMPLATE_MAX_LENGTH) { PostemTool.populateMessage( FacesMessage.SEVERITY_ERROR, "template_too_long", new Object[] { new Integer(this.newTemplate.trim().length()), new Integer(TEMPLATE_MAX_LENGTH) }); return "create_gradebook"; } } if (withHeader == true) { if (grades.getHeaders() != null) { PostemTool.populateMessage(FacesMessage.SEVERITY_INFO, "has_headers", new Object[] {}); } } if (grades.getStudents() != null) { PostemTool.populateMessage( FacesMessage.SEVERITY_INFO, "has_students", new Object[] {new Integer(grades.getStudents().size())}); } if (withHeader == true) { currentGradebook.setHeadings(grades.getHeaders()); } List slist = grades.getStudents(); if (oldGradebook.getId() != null && !this.userPressedBack) { Set oldStudents = currentGradebook.getStudents(); oldGradebook.setStudents(oldStudents); } currentGradebook.setStudents(new TreeSet()); // gradebookManager.saveGradebook(currentGradebook); Iterator si = slist.iterator(); while (si.hasNext()) { List ss = (List) si.next(); String uname = ((String) ss.remove(0)).trim(); // logger.info("[POSTEM] processCreate -- adding student " + // uname); gradebookManager.createStudentGradesInGradebook(uname, ss, currentGradebook); if (currentGradebook.getStudents().size() == 1) { currentGradebook.setFirstUploadedUsername( uname); // otherwise, the verify screen shows first in ABC order } } } catch (DataFormatException exception) { /* * TODO: properly subclass exception in order to allow for localized * messages (add getRowNumber/setRowNumber). Set exception message to be * key in .properties file */ PostemTool.populateMessage( FacesMessage.SEVERITY_ERROR, exception.getMessage(), new Object[] {}); return "create_gradebook"; } catch (IdUnusedException e) { PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), new Object[] {}); return "create_gradebook"; } catch (TypeException e) { PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), new Object[] {}); return "create_gradebook"; } catch (PermissionException e) { PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), new Object[] {}); return "create_gradebook"; } catch (ServerOverloadException e) { PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), new Object[] {}); return "create_gradebook"; } catch (IOException e) { PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), new Object[] {}); return "create_gradebook"; } } else if (this.csv != null) { // logger.info("**** Non Null Empty CSV!"); PostemTool.populateMessage( FacesMessage.SEVERITY_ERROR, "has_students", new Object[] {new Integer(0)}); currentGradebook.setHeadings(new ArrayList()); if (oldGradebook.getId() != null) { Set oldStudents = currentGradebook.getStudents(); oldGradebook.setStudents(oldStudents); } currentGradebook.setStudents(new TreeSet()); } if (this.newTemplate != null && this.newTemplate.trim().length() > 0) { currentGradebook.setTemplate(gradebookManager.createTemplate(newTemplate.trim())); } else if (this.newTemplate != null) { // logger.info("*** Non Null Empty Template!"); currentGradebook.setTemplate(null); } /* * if("No".equals(this.release)) { currentGradebook.setReleased(new * Boolean(false)); //logger.info("Set to No, " + * currentGradebook.getReleased()); } else { * currentGradebook.setReleased(new Boolean(true)); //logger.info("Set to * Yes, " + currentGradebook.getReleased()); } */ // gradebookManager.saveGradebook(currentGradebook); // logger.info(currentGradebook.getId()); // currentGradebook = null; if ((this.csv != null && this.csv.trim().length() > 0) || (this.newTemplate != null && this.newTemplate.trim().length() > 0)) { this.csv = null; this.newTemplate = null; return "verify"; } Iterator oi = oldGradebook.getStudents().iterator(); while (oi.hasNext()) { gradebookManager.deleteStudentGrades((StudentGrades) oi.next()); } this.userId = SessionManager.getCurrentSessionUserId(); currentGradebook.setLastUpdated(new Timestamp(new Date().getTime())); currentGradebook.setLastUpdater(this.userId); gradebookManager.saveGradebook(currentGradebook); this.currentGradebook = null; this.oldGradebook = null; this.withHeader = true; // this.gradebooks = null; return "main"; }
public String initializeAction(Reference reference) { return BaseInteractionAction.getInitializationId( reference.getReference(), this.getTypeId(), this.getId()); }
public String getReferenceTitle(Reference ref) { if (ref != null && ref.getProperties() != null) { return (String) ref.getProperties().getProperty(ref.getProperties().getNamePropDisplayName()); } return null; }
/** {@inheritDoc} */ public void refreshUser(String userId) { if ((m_provider == null) || (userId == null)) return; try { String eid = userDirectoryService().getUserEid(userId); // wrap the provided map in our special map that will deal with compound provider ids Map providerGrants = new ProviderMap(m_provider, m_provider.getGroupRolesForUser(eid)); m_storage.refreshUser(userId, providerGrants); // update site security for this user - get the user's realms for the three site locks Set updAuthzGroups = getAuthzGroupsIsAllowed(userId, SiteService.SECURE_UPDATE_SITE, null); Set unpAuthzGroups = getAuthzGroupsIsAllowed(userId, SiteService.SITE_VISIT_UNPUBLISHED, null); Set visitAuthzGroups = getAuthzGroupsIsAllowed(userId, SiteService.SITE_VISIT, null); // convert from azGroup ids (potential site references) to site ids for those that are site, // skipping special and user sites other than our user's Set updSites = new HashSet(); for (Iterator i = updAuthzGroups.iterator(); i.hasNext(); ) { String azGroupId = (String) i.next(); Reference ref = entityManager().newReference(azGroupId); if ((SiteService.APPLICATION_ID.equals(ref.getType())) && SiteService.SITE_SUBTYPE.equals(ref.getSubType()) && !SiteService.isSpecialSite(ref.getId()) && (!SiteService.isUserSite(ref.getId()) || userId.equals(SiteService.getSiteUserId(ref.getId())))) { updSites.add(ref.getId()); } } Set unpSites = new HashSet(); for (Iterator i = unpAuthzGroups.iterator(); i.hasNext(); ) { String azGroupId = (String) i.next(); Reference ref = entityManager().newReference(azGroupId); if ((SiteService.APPLICATION_ID.equals(ref.getType())) && SiteService.SITE_SUBTYPE.equals(ref.getSubType()) && !SiteService.isSpecialSite(ref.getId()) && (!SiteService.isUserSite(ref.getId()) || userId.equals(SiteService.getSiteUserId(ref.getId())))) { unpSites.add(ref.getId()); } } Set visitSites = new HashSet(); for (Iterator i = visitAuthzGroups.iterator(); i.hasNext(); ) { String azGroupId = (String) i.next(); Reference ref = entityManager().newReference(azGroupId); if ((SiteService.APPLICATION_ID.equals(ref.getType())) && SiteService.SITE_SUBTYPE.equals(ref.getSubType()) && !SiteService.isSpecialSite(ref.getId()) && (!SiteService.isUserSite(ref.getId()) || userId.equals(SiteService.getSiteUserId(ref.getId())))) { visitSites.add(ref.getId()); } } SiteService.setUserSecurity(userId, updSites, unpSites, visitSites); } catch (UserNotDefinedException e) { M_log.warn("refreshUser: cannot find eid for user: " + userId); } }