@Override protected void event(UserRequest ureq, Controller source, Event event) { if (event instanceof OpenAuthorProfilEvent) { OpenAuthorProfilEvent uriEvent = (OpenAuthorProfilEvent) event; Long identityKey = uriEvent.getKey(); if (identityKey == null) return; final Identity identity = BaseSecurityManager.getInstance().loadIdentityByKey(identityKey, false); if (identity == null) return; final HomePageConfig homePageConfig = HomePageConfigManagerImpl.getInstance().loadConfigFor(identity.getName()); ControllerCreator ctrlCreator = new ControllerCreator() { public Controller createController(UserRequest lureq, WindowControl lwControl) { HomePageDisplayController homePageCtrl = new HomePageDisplayController(lureq, lwControl, identity, homePageConfig); LayoutMain3ColsController layoutCtr = new LayoutMain3ColsController( lureq, lwControl, null, null, homePageCtrl.getInitialComponent(), null); // dispose glossary on layout dispose layoutCtr.addDisposableChildController(homePageCtrl); return layoutCtr; } }; ControllerCreator layoutCtrlr = BaseFullWebappPopupLayoutFactory.createAuthMinimalPopupLayout(ureq, ctrlCreator); // open in new browser window openInNewBrowserWindow(ureq, layoutCtrlr); return; // immediate return after opening new browser window! } else { super.event(ureq, source, event); } }
@Test public void mergeTwoUserPolicies() { // create a map final PortfolioStructureMap map = epFrontendManager.createAndPersistPortfolioDefaultMap( ident1, "Remove policies", "Description"); final PortfolioStructure page1 = epFrontendManager.createAndPersistPortfolioPage(map, "Page policies", "Page description"); assertNotNull(page1); dbInstance.commitAndCloseSession(); // save a list of policies final List<EPMapPolicy> policies = new ArrayList<EPMapPolicy>(); // first user policy final EPMapPolicy userPolicy1 = new EPMapPolicy(); userPolicy1.setType(Type.user); userPolicy1.getIdentities().add(ident2); userPolicy1.getIdentities().add(ident3); policies.add(userPolicy1); // second user policy final EPMapPolicy userPolicy2 = new EPMapPolicy(); userPolicy2.setType(Type.user); userPolicy2.getIdentities().add(ident1); policies.add(userPolicy2); epFrontendManager.updateMapPolicies(map, policies); dbInstance.commitAndCloseSession(); // check if the policies are correctly merged final List<EPMapPolicy> mergedPolicies = epFrontendManager.getMapPolicies(map); assertNotNull(mergedPolicies); assertEquals(1, mergedPolicies.size()); final EPMapPolicy mergedPolicy = mergedPolicies.get(0); final List<Identity> identities = mergedPolicy.getIdentities(); assertEquals(3, identities.size()); int count1, count2, count3; count1 = count2 = count3 = 0; for (final Identity identity : identities) { if (identity.equalsByPersistableKey(ident1)) { count1++; } else if (identity.equalsByPersistableKey(ident2)) { count2++; } else if (identity.equalsByPersistableKey(ident3)) { count3++; } } assertEquals(1, count1); assertEquals(1, count2); assertEquals(1, count3); }
@Override protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) { Boolean hasIdentitesToDelete = (Boolean) getFromRunContext("hasIdentitiesToDelete"); FormLayoutContainer textContainer = FormLayoutContainer.createCustomFormLayout( "index", getTranslator(), velocity_root + "/delet_step01.html"); formLayout.add(textContainer); textContainer.contextPut("hasIdentitesToDelete", hasIdentitesToDelete); if (hasIdentitesToDelete != null && !hasIdentitesToDelete.booleanValue()) { setNextStep(Step.NOSTEP); return; } Map<String, String> reqProbertyMap = new HashMap<String, String>(syncConfiguration.getUserAttributeMap()); Collection<String> reqProberty = reqProbertyMap.values(); reqProberty.remove(LDAPConstants.LDAP_USER_IDENTIFYER); @SuppressWarnings("unchecked") List<Identity> identitiesToDelete = (List<Identity>) getFromRunContext("identitiesToDelete"); for (Identity identityToDelete : identitiesToDelete) { List<String> rowData = new ArrayList<>(); rowData.add(identityToDelete.getName()); for (String property : reqProberty) { rowData.add(identityToDelete.getUser().getProperty(property, null)); } } FlexiTableColumnModel tableColumnModel = FlexiTableDataModelFactory.createFlexiTableColumnModel(); int colPos = 0; tableColumnModel.addFlexiColumnModel(new DefaultFlexiColumnModel("username", 10000)); List<UserPropertyHandler> handlers = new ArrayList<>(); for (String property : reqProberty) { List<UserPropertyHandler> properHandlerList = UserManager.getInstance().getAllUserPropertyHandlers(); for (UserPropertyHandler userProperty : properHandlerList) { if (userProperty.getName().equals(property)) { tableColumnModel.addFlexiColumnModel( new DefaultFlexiColumnModel(userProperty.i18nColumnDescriptorLabelKey(), colPos++)); handlers.add(userProperty); } } } FlexiTableDataModel<Identity> tableDataModel = new IdentityFlexiTableModel(identitiesToDelete, tableColumnModel, handlers, getLocale()); uifactory.addTableElement( getWindowControl(), "newUsers", tableDataModel, getTranslator(), formLayout); }
public AssessedIdentityRepositoryEntryController( UserRequest ureq, WindowControl wControl, TooledStackedPanel stackPanel, RepositoryEntry assessableEntry, Identity assessedIdentity, AssessableResource element) { super(ureq, wControl); this.stackPanel = stackPanel; this.assessedIdentity = assessedIdentity; identityAssessmentVC = createVelocityContainer("identity_personal_infos"); identityAssessmentVC.contextPut("user", assessedIdentity.getUser()); infosController = new AssessedIdentityLargeInfosController(ureq, wControl, assessedIdentity); listenTo(infosController); identityAssessmentVC.put("identityInfos", infosController.getInitialComponent()); RepositoryHandler handler = repositoryHandlerFactory.getRepositoryHandler(assessableEntry); if (handler.supportsAssessmentDetails()) { detailsCtrl = handler.createAssessmentDetailsController( assessableEntry, ureq, getWindowControl(), stackPanel, assessedIdentity); listenTo(detailsCtrl); identityAssessmentVC.put("details", detailsCtrl.getInitialComponent()); } assessmentForm = new AssessmentForm(ureq, getWindowControl(), assessedIdentity, assessableEntry, element); listenTo(assessmentForm); identityAssessmentVC.put("assessmentForm", assessmentForm.getInitialComponent()); putInitialPanel(identityAssessmentVC); }
private void deleteIdentities(List<Identity> identities, List<String> errors) { for (Identity id : identities) { try { UserDeletionManager.getInstance().deleteIdentity(id); } catch (Exception e) { errors.add(id.getName()); logError("", e); } finally { try { DBFactory.getInstance().intermediateCommit(); } catch (Exception e) { logError("", e); } } } }
private void sendFeedback(List<BulkAssessmentFeedback> feedbacks) { if (task == null) { log.error("Haven't a task to know creator and modifiers of the task", null); return; } Identity creator = task.getCreator(); String language = creator.getUser().getPreferences().getLanguage(); Locale locale = I18nManager.getInstance().getLocaleOrDefault(language); Translator translator = Util.createPackageTranslator( BulkAssessmentOverviewController.class, locale, Util.createPackageTranslator(AssessmentManager.class, locale)); MailManager mailManager = CoreSpringFactory.getImpl(MailManager.class); TaskExecutorManager taskManager = CoreSpringFactory.getImpl(TaskExecutorManager.class); String feedbackStr = renderFeedback(feedbacks, translator); MailBundle mail = new MailBundle(); mail.setToId(creator); mail.setFrom(WebappHelper.getMailConfig("mailReplyTo")); List<Identity> modifiers = taskManager.getModifiers(task); if (modifiers.size() > 0) { ContactList cc = new ContactList("CC"); cc.addAllIdentites(modifiers); mail.setContactList(cc); } String businessPath = ""; ICourse course = CourseFactory.loadCourse(courseRes); CourseNode node = course.getRunStructure().getNode(courseNodeIdent); String courseTitle = course.getCourseTitle(); String nodeTitle = node.getShortTitle(); String numOfAssessedIds = Integer.toString(datas == null ? 0 : datas.getRowsSize()); String date = Formatter.getInstance(locale).formatDateAndTime(new Date()); mail.setContext(new MailContextImpl(courseRes, courseNodeIdent, businessPath)); String subject = translator.translate("confirmation.mail.subject", new String[] {courseTitle, nodeTitle}); String body = translator.translate( "confirmation.mail.body", new String[] {courseTitle, nodeTitle, feedbackStr, numOfAssessedIds, date}); mail.setContent(subject, body); mailManager.sendMessage(mail); }
/** * Check to see if a resource is currently write locked. * * @param path Path of the resource * @param ifHeader "If" HTTP header which was included in the request * @return boolean true if the resource is locked (and no appropriate lock token has been found * for at least one of the non-shared locks which are present on the resource). */ public boolean isLocked(WebResource resource, String ifHeader, Identity identity) { // Checking resource locks String path = resource.getPath(); // check if someone else as not set a lock on the resource if (resource instanceof VFSResource) { VFSResource vfsResource = (VFSResource) resource; Long lockedBy = getMetaLockedBy(vfsResource.getItem()); if (lockedBy != null && !lockedBy.equals(identity.getKey())) { return true; } } File file = extractFile(resource); if (file == null) { return false; // lock only file } LockInfo lock = fileLocks.get(file); if (lock != null && lock.hasExpired()) { fileLocks.remove(file); } else if (lock != null) { // At least one of the tokens of the locks must have been given Iterator<String> tokenList = lock.tokens(); boolean tokenMatch = false; while (tokenList.hasNext()) { String token = tokenList.next(); if (ifHeader.indexOf(token) != -1) { tokenMatch = true; break; } } if (!tokenMatch) return true; } // Checking inheritable collection locks Enumeration<LockInfo> collectionLocksList = collectionLocks.elements(); while (collectionLocksList.hasMoreElements()) { lock = collectionLocksList.nextElement(); if (lock.hasExpired()) { collectionLocks.removeElement(lock); } else if (path.startsWith(lock.getWebPath())) { Iterator<String> tokenList = lock.tokens(); boolean tokenMatch = false; while (tokenList.hasNext()) { String token = tokenList.next(); if (ifHeader.indexOf(token) != -1) { tokenMatch = true; break; } } if (!tokenMatch) return true; } } return false; }
@Override protected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) { if (source instanceof MultipleSelectionElement) { MultipleSelectionElement publishCheckbox = (MultipleSelectionElement) source; if (publishCheckbox.isEnabled()) { boolean enabled = publishCheckbox.isAtLeastSelected(1); String propName = (String) publishCheckbox.getUserObject(); // load and update config HomePageConfig conf = hpcm.loadConfigFor(identityToModify.getName()); conf.setEnabled(propName, enabled); hpcm.saveConfigTo(identityToModify.getName(), conf); updatePreview(ureq, conf); } } super.formInnerEvent(ureq, source, event); }
/** @return true If the lock owner is someone else or if it's a WebDAV lock */ @Override public boolean isLockedForMe(VFSItem item, Identity me, Roles roles) { File file = extractFile(item); if (file != null && fileLocks.containsKey(file)) { LockInfo lock = fileLocks.get(file); if (lock != null && lock.hasExpired()) { // LOCK resourceLocks.remove(lock.getWebPath()); fileLocks.remove(file); } else { Long lockedBy = lock.getLockedBy(); return (lockedBy != null && !lockedBy.equals(me.getKey())) || lock.isWebDAVLock(); } } Long lockedBy = getMetaLockedBy(item); return (lockedBy != null && !lockedBy.equals(me.getKey())); }
/** @return The name of the modifier */ public String getModifier() { String modifierName = null; if (modifierKey > 0) { Identity identity = BaseSecurityManager.getInstance().loadIdentityByKey(modifierKey, false); if (identity != null) { User user = identity.getUser(); if (user == null) { modifierName = modifier = identity.getName(); } else { modifierName = modifier = CoreSpringFactory.getImpl(UserManager.class).getUserDisplayName(identity); } } } if (modifierName == null && StringHelper.containsNonWhitespace(modifier)) { modifierName = modifier; } return modifierName; }
private UserSession afterAuthorization(Identity identity, HttpServletRequest request) { UserSession usess = sessionManager.getUserSession(request); synchronized (usess) { // double check to prevent severals concurrent login if (usess.isAuthenticated()) { return usess; } sessionManager.signOffAndClear(usess); usess.setIdentity(identity); UserDeletionManager.getInstance().setIdentityAsActiv(identity); // set the roles (admin, author, guest) Roles roles = BaseSecurityManager.getInstance().getRoles(identity); usess.setRoles(roles); // set session info SessionInfo sinfo = new SessionInfo(identity.getKey(), identity.getName(), request.getSession()); User usr = identity.getUser(); sinfo.setFirstname(usr.getProperty(UserConstants.FIRSTNAME, null)); sinfo.setLastname(usr.getProperty(UserConstants.LASTNAME, null)); String remoteAddr = request.getRemoteAddr(); sinfo.setFromIP(remoteAddr); sinfo.setFromFQN(remoteAddr); try { InetAddress[] iaddr = InetAddress.getAllByName(request.getRemoteAddr()); if (iaddr.length > 0) sinfo.setFromFQN(iaddr[0].getHostName()); } catch (UnknownHostException e) { // ok, already set IP as FQDN } sinfo.setAuthProvider(BaseSecurityModule.getDefaultAuthProviderIdentifier()); sinfo.setUserAgent(request.getHeader("User-Agent")); sinfo.setSecure(request.isSecure()); sinfo.setWebDAV(true); sinfo.setWebModeFromUreq(null); // set session info for this session usess.setSessionInfo(sinfo); // sessionManager.signOn(usess); return usess; } }
/** internal counter method * */ private synchronized void returnSlot(final Identity identity) { identitiesOfJobsCurrentlyRunning_.remove(identity); log_.info( "returnSlot: user " + identity.getName() + " returns a slot. Running count: " + identitiesOfJobsCurrentlyRunning_.size() + ", Total pending jobs: " + waitingCnt_); notifyAll(); }
@Override public Object getValueAt(int row, int col) { Identity identity = objects.get(row); switch (col) { case 0: return identity.getUser().getProperty(UserConstants.FIRSTNAME, getLocale()); case 1: return identity.getUser().getProperty(UserConstants.LASTNAME, getLocale()); case 2: return identity.getUser().getProperty(UserConstants.EMAIL, getLocale()); case 3: return Boolean.TRUE; case 4: return Boolean.TRUE; default: return "error"; } }
/** * Find all ResultSets for certain identity. * * @param identity * @param assessmentID * @return */ public List<QTIResultSet> findQtiResultSets(Identity identity) { StringBuilder sb = new StringBuilder(); sb.append("select rset from ") .append(QTIResultSet.class.getName()) .append(" as rset") .append(" where rset.identity.key=:identityKey"); return dbInstance .getCurrentEntityManager() .createQuery(sb.toString(), QTIResultSet.class) .setParameter("identityKey", identity.getKey()) .getResultList(); }
/** @return The name of the author */ public String getAuthor() { String authorName = null; if (authorKey > 0) { Identity identity = BaseSecurityManager.getInstance().loadIdentityByKey(authorKey, false); if (identity != null) { User user = identity.getUser(); if (user == null) { authorName = author = identity.getName(); } else { authorName = author = user.getProperty(UserConstants.FIRSTNAME, null) + " " + user.getProperty(UserConstants.LASTNAME, null); } } } if (authorName == null && StringHelper.containsNonWhitespace(author)) { authorName = author; } return authorName; }
private void doIdentityAssessmentOverview(UserRequest ureq, boolean initTable) { if (identityOverviewVC == null) { identityOverviewVC = createVelocityContainer("identityoverview"); if (headers) { backLink = LinkFactory.createLinkBack(identityOverviewVC, this); Identity assessedIdentity = assessedUserCourseEnvironment.getIdentityEnvironment().getIdentity(); identityOverviewVC.contextPut("user", assessedIdentity.getUser()); } } if (initTable) { assessedUserCourseEnvironment.getScoreAccounting().evaluateAll(); assessmentOverviewCtr = new IdentityAssessmentOverviewController( ureq, getWindowControl(), assessedUserCourseEnvironment, mayEdit, false, true); listenTo(assessmentOverviewCtr); identityOverviewVC.put( "assessmentOverviewTable", assessmentOverviewCtr.getInitialComponent()); } main.setContent(identityOverviewVC); }
/** * Return the target folder of the assessed identity. This is a factory method which take care of * the type of the course node. * * @param uce * @param courseNode * @param identity * @return */ private VFSContainer getReturnBox( UserCourseEnvironment uce, CourseNode courseNode, Identity identity) { VFSContainer returnContainer = null; if (courseNode instanceof GTACourseNode) { final GTAManager gtaManager = CoreSpringFactory.getImpl(GTAManager.class); CourseEnvironment courseEnv = uce.getCourseEnvironment(); returnContainer = gtaManager.getCorrectionContainer(courseEnv, (GTACourseNode) courseNode, identity); } else { String returnPath = ReturnboxController.getReturnboxPathRelToFolderRoot( uce.getCourseEnvironment(), courseNode); OlatRootFolderImpl rootFolder = new OlatRootFolderImpl(returnPath, null); VFSItem assessedItem = rootFolder.resolve(identity.getName()); if (assessedItem == null) { returnContainer = rootFolder.createChildContainer(identity.getName()); } else if (assessedItem instanceof VFSContainer) { returnContainer = (VFSContainer) assessedItem; } } return returnContainer; }
/** Same workflow as the repository. This workflow is pretty critical. */ @Test public void isStructuredMapOwner() { final OLATResource resource = epStructureManager.createPortfolioMapTemplateResource(); // create a repository entry final RepositoryEntry addedEntry = repositoryManager.createRepositoryEntryInstance(ident1.getName()); addedEntry.setCanDownload(false); addedEntry.setCanLaunch(true); addedEntry.setDisplayname("test repo"); addedEntry.setResourcename("-"); addedEntry.setAccess(RepositoryEntry.ACC_OWNERS); // Set the resource on the repository entry and save the entry. final OLATResource ores = resourceManager.findOrPersistResourceable(resource); addedEntry.setOlatResource(ores); // create security group final SecurityGroup newGroup = securityManager.createAndPersistSecurityGroup(); securityManager.createAndPersistPolicy(newGroup, Constants.PERMISSION_ACCESS, newGroup); securityManager.createAndPersistPolicy( newGroup, Constants.PERMISSION_HASROLE, EPStructureManager.ORES_MAPOWNER); securityManager.addIdentityToSecurityGroup(ident1, newGroup); addedEntry.setOwnerGroup(newGroup); repositoryManager.saveRepositoryEntry(addedEntry); dbInstance.commitAndCloseSession(); // create the template owned by ident1 final PortfolioStructureMap template = epStructureManager.createAndPersistPortfolioMapTemplateFromEntry(ident1, addedEntry); final PortfolioStructure page1 = epFrontendManager.createAndPersistPortfolioPage(template, "Page title", "Page description"); assertNotNull(page1); dbInstance.commitAndCloseSession(); // assign the template to ident2 final PortfolioStructureMap map = epFrontendManager.assignStructuredMapToUser(ident2, template, null, null, null, null); assertNotNull(map); dbInstance.commitAndCloseSession(); // check if ident2 is owner of the map assertTrue(epFrontendManager.isMapOwner(ident2, map.getOlatResource())); // check if ident1 is not the owner of the map assertFalse(epFrontendManager.isMapOwner(ident1, map.getOlatResource())); // check if ident1 is owner of the template assertTrue(epFrontendManager.isMapOwner(ident1, template.getOlatResource())); }
public static Document createDocument( final SearchResourceContext searchResourceContext, final WikiPage wikiPage) { final WikiPageDocument wikiPageDocument = new WikiPageDocument(); final long userId = wikiPage.getInitalAuthor(); if (userId != 0) { final Identity identity = identityManager.loadIdentityByKey(Long.valueOf(userId)); wikiPageDocument.setAuthor(identity.getName()); } wikiPageDocument.setTitle(wikiPage.getPageName()); wikiPageDocument.setContent(getContent(wikiPage)); wikiPageDocument.setCreatedDate(new Date(wikiPage.getCreationTime())); wikiPageDocument.setLastChange(new Date(wikiPage.getModificationTime())); wikiPageDocument.setResourceUrl(searchResourceContext.getResourceUrl()); wikiPageDocument.setDocumentType(searchResourceContext.getDocumentType()); wikiPageDocument.setCssIcon("o_wiki_icon"); wikiPageDocument.setParentContextType(searchResourceContext.getParentContextType()); wikiPageDocument.setParentContextName(searchResourceContext.getParentContextName()); if (log.isDebug()) { log.debug(wikiPageDocument.toString()); } return wikiPageDocument.getLuceneDocument(); }
private void doNoLockingEnrol(Identity i, SecurityGroup group) { // check that below max try { StringBuilder sb = new StringBuilder(); int cnt = BaseSecurityManager.getInstance().countIdentitiesOfSecurityGroup(group); sb.append("enrol:cnt:" + cnt); if (cnt < MAX_COUNT) { // now sleep a while to allow others to think also that there is still space left in the // group sleep(100); // now add the user to the security group sb.append(" adding " + i.getName() + ": current.. " + cnt + ", max = " + MAX_COUNT); BaseSecurityManager.getInstance().addIdentityToSecurityGroup(i, group); } log.info(sb.toString()); } catch (Exception e) { log.error("", e); } }
/** internal counter method * */ private synchronized void waitForSlot(final Identity identity) { waitingCnt_++; while (identitiesOfJobsCurrentlyRunning_.size() > concurrentExportsPerNode_ || identitiesOfJobsCurrentlyRunning_.contains(identity)) { try { log_.info( "waitForSlot: user " + identity.getName() + " wants to archive a course log, but the queue is full. Running count: " + identitiesOfJobsCurrentlyRunning_.size() + ". Total pending jobs: " + waitingCnt_); wait(); } catch (final InterruptedException ie) { // this empty catch is ok } } waitingCnt_--; identitiesOfJobsCurrentlyRunning_.add(identity); }
@Override public boolean lock(VFSItem item, Identity identity, Roles roles) { if (item instanceof MetaTagged) { MetaInfoFileImpl info = (MetaInfoFileImpl) ((MetaTagged) item).getMetaInfo(); info.setLockedBy(identity.getKey()); info.setLockedDate(new Date()); info.setLocked(true); info.write(); File file = extractFile(item); if (file != null && fileLocks.containsKey(file)) { LockInfo lock = fileLocks.get(file); if (lock != null) { lock.setVfsLock(true); } } return true; } return false; }
@Test public void binderAndSectionAndPageAccessRights() { Identity owner = JunitTestHelper.createAndPersistIdentityAsRndUser("port-u-3"); Identity coach = JunitTestHelper.createAndPersistIdentityAsRndUser("port-u-4"); Identity reviewer = JunitTestHelper.createAndPersistIdentityAsRndUser("port-u-5"); String title = "My published binder"; String summary = "My live"; Binder binder = portfolioService.createNewBinder(title, summary, null, owner); dbInstance.commit(); portfolioService.appendNewSection("Section", "Coached section", null, null, binder); dbInstance.commit(); List<Section> sections = portfolioService.getSections(binder); Section section = sections.get(0); portfolioService.appendNewPage(owner, "Reviewed page", "", null, null, section); portfolioService.addAccessRights(section, coach, PortfolioRoles.coach); dbInstance.commit(); List<Page> pages = portfolioService.getPages(section); Page page = pages.get(0); portfolioService.addAccessRights(page, reviewer, PortfolioRoles.reviewer); // load right List<AccessRights> rights = portfolioService.getAccessRights(binder); Assert.assertNotNull(rights); Assert.assertEquals(4, rights.size()); boolean foundOwner = false; boolean foundCoach = false; boolean foundReviewer = false; for (AccessRights right : rights) { if (PortfolioRoles.owner.equals(right.getRole()) && owner.equals(right.getIdentity())) { foundOwner = true; } else if (PortfolioRoles.coach.equals(right.getRole()) && coach.equals(right.getIdentity())) { foundCoach = true; } else if (PortfolioRoles.reviewer.equals(right.getRole()) && reviewer.equals(right.getIdentity())) { foundReviewer = true; } } Assert.assertTrue(foundOwner); Assert.assertTrue(foundCoach); Assert.assertTrue(foundReviewer); }
@Override public boolean move(VFSLeaf currentFile, VFSLeaf targetFile, Identity author) { VFSLeaf fCurrentVersions = getCanonicalVersionXmlFile(currentFile, true); Versions currentVersions = readVersions(currentFile, fCurrentVersions); boolean brandNewVersionFile = false; VFSLeaf fTargetVersions = getCanonicalVersionXmlFile(targetFile, false); if (fTargetVersions == null) { brandNewVersionFile = true; fTargetVersions = getCanonicalVersionXmlFile(targetFile, true); } Versions targetVersions = readVersions(targetFile, fTargetVersions); if (!(currentVersions instanceof VersionsFileImpl) || !(targetVersions instanceof VersionsFileImpl)) { return false; } VersionsFileImpl targetVersionsImpl = (VersionsFileImpl) targetVersions; if (author != null) { targetVersionsImpl.setAuthor(author.getName()); } if (brandNewVersionFile) { targetVersionsImpl.setCreator(currentVersions.getCreator()); targetVersionsImpl.setComment(currentVersions.getComment()); } boolean allOk = true; for (VFSRevision revision : currentVersions.getRevisions()) { allOk &= copyRevision(revision, fTargetVersions, targetVersionsImpl); } targetVersionsImpl.setRevisionNr(getNextRevisionNr(targetVersionsImpl)); XStreamHelper.writeObject(mystream, fTargetVersions, targetVersionsImpl); return allOk; }
/** * Get the resulkt sets. * * @param olatResource * @param olatResourceDetail * @param repositoryRef * @param identity May be null * @return List of resultsets */ public List<QTIResultSet> getResultSets( Long olatResource, String olatResourceDetail, Long repositoryRef, Identity identity) { StringBuilder sb = new StringBuilder(); sb.append("select rset from ") .append(QTIResultSet.class.getName()) .append(" as rset ") .append( "where rset.olatResource=:resId and rset.olatResourceDetail=:resSubPath and rset.repositoryRef=:repoKey"); if (identity != null) { sb.append(" and rset.identity.key=:identityKey "); } TypedQuery<QTIResultSet> query = dbInstance .getCurrentEntityManager() .createQuery(sb.toString(), QTIResultSet.class) .setParameter("resId", olatResource) .setParameter("resSubPath", olatResourceDetail) .setParameter("repoKey", repositoryRef); if (identity != null) { query.setParameter("identityKey", identity.getKey()); } return query.getResultList(); }
/** * @see * org.olat.core.commons.services.notifications.NotificationsHandler#createSubscriptionInfo(org.olat.core.commons.services.notifications.Subscriber, * java.util.Locale, java.util.Date) */ public SubscriptionInfo createSubscriptionInfo( final Subscriber subscriber, Locale locale, Date compareDate) { SubscriptionInfo si = null; Publisher p = subscriber.getPublisher(); if (!NotificationsUpgradeHelper.checkCourse(p)) { // course don't exist anymore NotificationsManager.getInstance().deactivate(p); return NotificationsManager.getInstance().getNoSubscriptionInfo(); } try { Date latestNews = p.getLatestNewsDate(); Identity identity = subscriber.getIdentity(); // do not try to create a subscription info if state is deleted - results in // exceptions, course // can't be loaded when already deleted if (NotificationsManager.getInstance().isPublisherValid(p) && compareDate.before(latestNews)) { Long courseId = new Long(p.getData()); final ICourse course = loadCourseFromId(courseId); if (course != null) { // course admins or users with the course right to have full access to // the assessment tool will have full access to user tests CourseGroupManager cgm = course.getCourseEnvironment().getCourseGroupManager(); final boolean hasFullAccess = (cgm.isIdentityCourseAdministrator(identity) ? true : cgm.hasRight(identity, CourseRights.RIGHT_ASSESSMENT)); final List<Identity> coachedUsers = new ArrayList<Identity>(); if (!hasFullAccess) { // initialize list of users, only when user has not full access List<BusinessGroup> coachedGroups = cgm.getOwnedBusinessGroups(identity); BusinessGroupService businessGroupService = CoreSpringFactory.getImpl(BusinessGroupService.class); List<Identity> coachedIdentites = businessGroupService.getMembers(coachedGroups, GroupRoles.participant.name()); coachedUsers.addAll(coachedIdentites); } List<AssessableCourseNode> testNodes = getCourseTestNodes(course); Translator translator = Util.createPackageTranslator(AssessmentNotificationsHandler.class, locale); for (AssessableCourseNode test : testNodes) { final CoursePropertyManager cpm = course.getCourseEnvironment().getCoursePropertyManager(); List<Property> scoreProperties = cpm.listCourseNodeProperties(test, null, null, AssessmentManager.SCORE); List<Property> attemptProperties = cpm.listCourseNodeProperties(test, null, null, AssessmentManager.ATTEMPTS); for (Property attemptProperty : attemptProperties) { Date modDate = attemptProperty.getLastModified(); Identity assessedIdentity = attemptProperty.getIdentity(); if (modDate.after(compareDate) && (hasFullAccess || PersistenceHelper.listContainsObjectByKey( coachedUsers, assessedIdentity))) { String score = null; for (Property scoreProperty : scoreProperties) { if (scoreProperty.getIdentity().equalsByPersistableKey(assessedIdentity)) { score = scoreProperty.getFloatValue().toString(); break; } } if (test instanceof ScormCourseNode) { ScormCourseNode scormTest = (ScormCourseNode) test; // check if completed or passed String status = ScormAssessmentManager.getInstance() .getLastLessonStatus( assessedIdentity.getName(), course.getCourseEnvironment(), scormTest); if (!"passed".equals(status) && !"completed".equals(status)) { continue; } } String desc; String type = translator.translate("notifications.entry." + test.getType()); if (score == null) { desc = translator.translate( "notifications.entry.attempt", new String[] { test.getShortTitle(), NotificationHelper.getFormatedName(assessedIdentity), type }); } else { desc = translator.translate( "notifications.entry", new String[] { test.getShortTitle(), NotificationHelper.getFormatedName(assessedIdentity), score, type }); } String urlToSend = null; String businessPath = null; if (p.getBusinessPath() != null) { businessPath = p.getBusinessPath() + "[assessmentTool:0][Identity:" + assessedIdentity.getKey() + "][CourseNode:" + test.getIdent() + "]"; urlToSend = BusinessControlFactory.getInstance() .getURLFromBusinessPathString(businessPath); } SubscriptionListItem subListItem = new SubscriptionListItem( desc, urlToSend, businessPath, modDate, CSS_CLASS_USER_ICON); if (si == null) { String title = translator.translate( "notifications.header", new String[] {course.getCourseTitle()}); String css = CourseNodeFactory.getInstance() .getCourseNodeConfigurationEvenForDisabledBB(test.getType()) .getIconCSSClass(); si = new SubscriptionInfo( subscriber.getKey(), p.getType(), new TitleItem(title, css), null); } si.addSubscriptionListItem(subListItem); } } } } } if (si == null) { si = NotificationsManager.getInstance().getNoSubscriptionInfo(); } return si; } catch (Exception e) { log.error("Error while creating assessment notifications", e); checkPublisher(p); return NotificationsManager.getInstance().getNoSubscriptionInfo(); } }
@Test public void testSync() { log.info("testing enrollment"); // ------------------ now check with lock ------------------- // create a group // create users final List<Identity> identities = new ArrayList<Identity>(); for (int i = 0; i < MAX_COUNT + MAX_USERS_MORE; i++) { Identity id = JunitTestHelper.createAndPersistIdentityAsUser( "u-" + i + "-" + UUID.randomUUID().toString()); identities.add(id); log.info("testSync: Identity=" + id.getName() + " created"); } dbInstance.closeSession(); final SecurityGroup group2 = BaseSecurityManager.getInstance().createAndPersistSecurityGroup(); // make sure the lock has been written to the disk (tests for createOrFind see other methods) dbInstance.closeSession(); // prepare threads int numOfThreads = MAX_COUNT + MAX_USERS_MORE; final CountDownLatch finishCount = new CountDownLatch(numOfThreads); // try to enrol all in the same group for (int i = 0; i < numOfThreads; i++) { final int j = i; new Thread( new Runnable() { public void run() { try { log.info("testSync: thread started j=" + j); Identity id = identities.get(j); // PLock p2 = pessimisticLockManager.findOrPersistPLock("befinsert"); assertNotNull(p2); doNoLockingEnrol(id, group2); dbInstance.commit(); dbInstance.closeSession(); } catch (Exception e) { e.printStackTrace(); } finally { finishCount.countDown(); } } }) .start(); } try { finishCount.await(120, TimeUnit.SECONDS); } catch (InterruptedException e) { log.error("", e); } // now count dbInstance.closeSession(); int cnt2 = BaseSecurityManager.getInstance().countIdentitiesOfSecurityGroup(group2); assertTrue( "cnt should be smaller or eq than allowed since synced with select for update. cnt:" + cnt2 + ", max " + MAX_COUNT, cnt2 <= MAX_COUNT); assertTrue( "cnt should be eq to allowed since synced with select for update. cnt:" + cnt2 + ", max " + MAX_COUNT, cnt2 == MAX_COUNT); log.info("cnt lock " + cnt2); }
/** Return the last name of the user */ @Override public String getTitle() { return identity.getUser().getProperty(UserConstants.LASTNAME, locale); }
@Override public OLATResourceable getOLATResourceable() { return new IdentityResourceable(identity.getKey()); }
@Test public void testDeleteUserData() { // create some identities and properties Identity id1 = JunitTestHelper.createAndPersistIdentityAsUser( "del-user-1-" + UUID.randomUUID().toString()); Identity id2 = JunitTestHelper.createAndPersistIdentityAsUser( "del-user-2-" + UUID.randomUUID().toString()); Property p10 = pm.createPropertyInstance( id1, null, null, "prop-del-1", "TestProperty", new Float(1.1), new Long(123456), "stringValue", "textValue"); pm.saveProperty(p10); Property p11 = pm.createPropertyInstance( id1, null, null, "prop-del-2", "TestProperty", new Float(1.1), new Long(123456), "stringValue", "textValue"); pm.saveProperty(p11); Property p20 = pm.createPropertyInstance( id2, null, null, "prop-del-3", "TestProperty", new Float(1.1), new Long(123456), "stringValue", "textValue"); pm.saveProperty(p20); dbInstance.commitAndCloseSession(); // delete user 1 datas pm.deleteUserData(id1, "del-" + id1.getName(), null); dbInstance.commitAndCloseSession(); // check if really deleted Property p10x = pm.findUserProperty(id1, "prop-del-1", "TestProperty"); assertNull(p10x); Property p11x = pm.findUserProperty(id1, "prop-del-2", "TestProperty"); assertNull(p11x); // check if id2 has still its properties Property p20x = pm.findUserProperty(id2, "prop-del-3", "TestProperty"); assertNotNull(p20x); }