diff --git a/src/main/java/org/olat/admin/user/bulkChange/UserBulkChangeManager.java b/src/main/java/org/olat/admin/user/bulkChange/UserBulkChangeManager.java index ad9e642aeb8358d67e2c40b4b69aded0e64af192..7e43baad9e282deae7e6a5b3d4ef71891a2ff976 100644 --- a/src/main/java/org/olat/admin/user/bulkChange/UserBulkChangeManager.java +++ b/src/main/java/org/olat/admin/user/bulkChange/UserBulkChangeManager.java @@ -52,6 +52,7 @@ import org.olat.core.manager.BasicManager; import org.olat.core.util.StringHelper; import org.olat.core.util.Util; import org.olat.group.BusinessGroupService; +import org.olat.group.model.AddToGroupsEvent; import org.olat.login.auth.OLATAuthManager; import org.olat.user.UserManager; import org.olat.user.propertyhandlers.UserPropertyHandler; @@ -189,7 +190,8 @@ public class UserBulkChangeManager extends BasicManager { // FXOLAT-101: add identity to new groups: if (ownGroups.size() != 0 || partGroups.size() != 0){ BusinessGroupService bgs = CoreSpringFactory.getImpl(BusinessGroupService.class); - bgs.addIdentityToGroups(ownGroups, partGroups, mailGroups, identity, addingIdentity); + AddToGroupsEvent groupsEv = new AddToGroupsEvent(ownGroups, partGroups, mailGroups); + bgs.addIdentityToGroups(groupsEv, identity, addingIdentity); } // set status diff --git a/src/main/java/org/olat/admin/user/groups/GroupOverviewController.java b/src/main/java/org/olat/admin/user/groups/GroupOverviewController.java index 05af75f7931377f98e1b2ddce2029f48409f817b..199a4a22ca0f5c2add13a7df53c96c4f54dc24a8 100644 --- a/src/main/java/org/olat/admin/user/groups/GroupOverviewController.java +++ b/src/main/java/org/olat/admin/user/groups/GroupOverviewController.java @@ -58,6 +58,7 @@ import org.olat.core.util.mail.MailerWithTemplate; import org.olat.core.util.notifications.NotificationHelper; import org.olat.group.BusinessGroup; import org.olat.group.BusinessGroupService; +import org.olat.group.model.AddToGroupsEvent; import org.olat.group.ui.BGConfigFlags; import org.olat.group.ui.BGControllerFactory; import org.olat.group.ui.BGMailHelper; diff --git a/src/main/java/org/olat/admin/user/groups/GroupSearchController.java b/src/main/java/org/olat/admin/user/groups/GroupSearchController.java index 0d9e23df1f7b7e6aaf316078ae8ac6e44719f49c..a1b232d02020cc9287dd083bf07e147bfc94e26d 100644 --- a/src/main/java/org/olat/admin/user/groups/GroupSearchController.java +++ b/src/main/java/org/olat/admin/user/groups/GroupSearchController.java @@ -46,6 +46,7 @@ import org.olat.core.gui.translator.Translator; import org.olat.core.util.StringHelper; import org.olat.core.util.Util; import org.olat.group.BusinessGroupService; +import org.olat.group.model.AddToGroupsEvent; import org.olat.group.ui.BusinessGroupTableModel; /** diff --git a/src/main/java/org/olat/admin/user/imp/UserImportController.java b/src/main/java/org/olat/admin/user/imp/UserImportController.java index 63f37457314a3f05544cfa862af1fe648382e949..d390b39421000b326a4eb3960fedb9ba3e0f9e15 100644 --- a/src/main/java/org/olat/admin/user/imp/UserImportController.java +++ b/src/main/java/org/olat/admin/user/imp/UserImportController.java @@ -49,6 +49,7 @@ import org.olat.core.id.Identity; import org.olat.core.id.User; import org.olat.core.util.StringHelper; import org.olat.group.BusinessGroupService; +import org.olat.group.model.AddToGroupsEvent; import org.olat.user.UserManager; import org.olat.user.propertyhandlers.UserPropertyHandler; @@ -210,7 +211,8 @@ public class UserImportController extends BasicController { ident = BaseSecurityManager.getInstance().findIdentityByName(identName); } if(ident != null){ - businessGroupService.addIdentityToGroups(ownGroups, partGroups, mailGroups, ident, addingIdentity); + AddToGroupsEvent groupsEv = new AddToGroupsEvent(ownGroups, partGroups, mailGroups); + businessGroupService.addIdentityToGroups(groupsEv, ident, addingIdentity); counter ++; if (counter % 5 == 0) { DBFactory.getInstance().intermediateCommit(); diff --git a/src/main/java/org/olat/basesecurity/BaseSecurityManager.java b/src/main/java/org/olat/basesecurity/BaseSecurityManager.java index 1594f89a40506511e1463360fbca62039ba58497..b72b57e64525a5375d156ce1e96facdbdbe5eefa 100644 --- a/src/main/java/org/olat/basesecurity/BaseSecurityManager.java +++ b/src/main/java/org/olat/basesecurity/BaseSecurityManager.java @@ -35,7 +35,6 @@ import java.util.Locale; import java.util.Map; import java.util.UUID; -import org.hibernate.Hibernate; import org.hibernate.type.StandardBasicTypes; import org.hibernate.type.Type; import org.olat.admin.quota.GenericQuotaEditController; diff --git a/src/main/java/org/olat/core/commons/persistence/DBManager.java b/src/main/java/org/olat/core/commons/persistence/DBManager.java index 3c472c5790ae59aff60bf07a946422ac92d458af..086298f2b6ab0100409b3cf3f97525daec81039d 100644 --- a/src/main/java/org/olat/core/commons/persistence/DBManager.java +++ b/src/main/java/org/olat/core/commons/persistence/DBManager.java @@ -96,7 +96,8 @@ class DBManager extends BasicManager { throw new DBRuntimeException("cannot delete in a transaction that is rolledback or committed " + o); } try { - getSession().delete(o); + Object relaoded = getSession().merge(o); + getSession().delete(relaoded); if (isLogDebugEnabled()) { logDebug("delete (trans "+trx.hashCode()+") class "+o.getClass().getName()+" = "+o.toString()); } diff --git a/src/main/java/org/olat/course/_spring/courseContext.xml b/src/main/java/org/olat/course/_spring/courseContext.xml index 2904c41cf0d12ad265b8374f0c63625f1a42eaf6..e6d338367c10d1d7e95b1c1caf5ad47954386d02 100644 --- a/src/main/java/org/olat/course/_spring/courseContext.xml +++ b/src/main/java/org/olat/course/_spring/courseContext.xml @@ -81,7 +81,7 @@ </bean> -<bean id="courseFactory" class="org.olat.course.CourseFactory" depends-on="businessGroupManager"> +<bean id="courseFactory" class="org.olat.course.CourseFactory" depends-on="businessGroupService"> <constructor-arg index="0" ref="coordinatorManager" /> <constructor-arg index="1" ref="repositoryManager" /> <constructor-arg index="2" ref="resourceManager" /> diff --git a/src/main/java/org/olat/course/condition/interpreter/InLearningGroupFunction.java b/src/main/java/org/olat/course/condition/interpreter/InLearningGroupFunction.java index 248bfd3c1a5879c4b68725afea12ef0931e072e9..624570e63214e5b76ea6534610a2c36161e70914 100644 --- a/src/main/java/org/olat/course/condition/interpreter/InLearningGroupFunction.java +++ b/src/main/java/org/olat/course/condition/interpreter/InLearningGroupFunction.java @@ -85,7 +85,7 @@ public class InLearningGroupFunction extends AbstractFunction { CourseGroupManager cgm = getUserCourseEnv().getCourseEnvironment().getCourseGroupManager(); //System.out.println("todo: check if "+(ident==null? "n/a":ident.getName())+" is in group "+groupName); - return cgm.isIdentityInLearningGroup(ident,groupName) ? ConditionInterpreter.INT_TRUE: ConditionInterpreter.INT_FALSE; + return cgm.isIdentityInGroup(ident,groupName) ? ConditionInterpreter.INT_TRUE: ConditionInterpreter.INT_FALSE; } protected Object defaultValue() { diff --git a/src/main/java/org/olat/course/condition/interpreter/InRightGroupFunction.java b/src/main/java/org/olat/course/condition/interpreter/InRightGroupFunction.java index d4cafa8181dab43f95a9468026dacc92a0787526..e6cd6063a05299462e8cf947f8cacc6516241d8a 100644 --- a/src/main/java/org/olat/course/condition/interpreter/InRightGroupFunction.java +++ b/src/main/java/org/olat/course/condition/interpreter/InRightGroupFunction.java @@ -87,7 +87,7 @@ public class InRightGroupFunction extends AbstractFunction { CourseGroupManager cgm = getUserCourseEnv().getCourseEnvironment().getCourseGroupManager(); - return cgm.isIdentityInRightGroup(ident,groupName) ? ConditionInterpreter.INT_TRUE: ConditionInterpreter.INT_FALSE; + return cgm.isIdentityInGroup(ident,groupName) ? ConditionInterpreter.INT_TRUE: ConditionInterpreter.INT_FALSE; } protected Object defaultValue() { diff --git a/src/main/java/org/olat/course/groupsandrights/CourseGroupManager.java b/src/main/java/org/olat/course/groupsandrights/CourseGroupManager.java index fd10020ed79c661c22a05bdcb1fd0f8245c4a74f..2158f84307c07b65fab7d98ae43c8e3c7b35e14a 100644 --- a/src/main/java/org/olat/course/groupsandrights/CourseGroupManager.java +++ b/src/main/java/org/olat/course/groupsandrights/CourseGroupManager.java @@ -76,7 +76,7 @@ public interface CourseGroupManager { * @param groupName * @return true if user is in learning group, false otherwhise */ - public boolean isIdentityInLearningGroup(Identity identity, String groupName); + public boolean isIdentityInGroup(Identity identity, String groupName); /** * Checks whether a set of learning groups with an identical name are full or not. @@ -87,15 +87,6 @@ public interface CourseGroupManager { */ public boolean isLearningGroupFull(String groupName); - /** - * Checks if an identity is in a right group with the given name in any - * contexts of this course - * - * @param identity - * @param groupName - * @return true if user is in right group, false otherwhise - */ - public boolean isIdentityInRightGroup(Identity identity, String groupName); /** * Checks if an identity is in any learning areas with the given name in any @@ -131,21 +122,13 @@ public interface CourseGroupManager { */ public boolean isIdentityCourseParticipant(Identity identity); - /** - * Checks if user is participant in any right group of this course - * - * @param identity - * @return boolean - */ - public boolean isIdentityParticipantInAnyRightGroup(Identity identity); - /** * Checks if user is participant in any learning group of this course * * @param identity * @return boolean */ - public boolean isIdentityParticipantInAnyLearningGroup(Identity identity); + public boolean isIdentityParticipantInAnyGroup(Identity identity); /** * @return A list of all learning group from all learning group contexts of diff --git a/src/main/java/org/olat/course/groupsandrights/PersistingCourseGroupManager.java b/src/main/java/org/olat/course/groupsandrights/PersistingCourseGroupManager.java index 8655fa97fbcfd97028527c9911a30b60fd0cff7b..3b1f56231f93d79c71bf67ca24974d059ea31ce9 100644 --- a/src/main/java/org/olat/course/groupsandrights/PersistingCourseGroupManager.java +++ b/src/main/java/org/olat/course/groupsandrights/PersistingCourseGroupManager.java @@ -127,7 +127,7 @@ public class PersistingCourseGroupManager extends BasicManager implements Course * @see org.olat.course.groupsandrights.CourseGroupManager#isIdentityInLearningGroup(org.olat.core.id.Identity, * java.lang.String, java.lang.String) */ - public boolean isIdentityInLearningGroup(Identity identity, String groupName) { + public boolean isIdentityInGroup(Identity identity, String groupName) { return businessGroupService.isIdentityInBusinessGroup(identity, groupName, BusinessGroup.TYPE_LEARNINGROUP, true, true, courseResource); } @@ -172,14 +172,6 @@ public class PersistingCourseGroupManager extends BasicManager implements Course } } - /** - * @see org.olat.course.groupsandrights.CourseGroupManager#isIdentityInRightGroup(org.olat.core.id.Identity, - * java.lang.String) - */ - public boolean isIdentityInRightGroup(Identity identity, String groupName) { - return businessGroupService.isIdentityInBusinessGroup(identity, groupName, BusinessGroup.TYPE_RIGHTGROUP, true, true, courseResource); - } - /** * @see org.olat.course.groupsandrights.CourseGroupManager#isIdentityInLearningArea(org.olat.core.id.Identity, * java.lang.String) @@ -359,17 +351,10 @@ public class PersistingCourseGroupManager extends BasicManager implements Course /** * @see org.olat.course.groupsandrights.CourseGroupManager#isIdentityParticipantInAnyLearningGroup(org.olat.core.id.Identity) */ - public boolean isIdentityParticipantInAnyLearningGroup(Identity identity) { + public boolean isIdentityParticipantInAnyGroup(Identity identity) { return businessGroupService.isIdentityInBusinessGroup(identity, null, BusinessGroup.TYPE_LEARNINGROUP, false, true, courseResource); } - /** - * @see org.olat.course.groupsandrights.CourseGroupManager#isIdentityParticipantInAnyRightGroup(org.olat.core.id.Identity) - */ - public boolean isIdentityParticipantInAnyRightGroup(Identity identity) { - return businessGroupService.isIdentityInBusinessGroup(identity, null, BusinessGroup.TYPE_RIGHTGROUP, false, true, courseResource); - } - /** * @see org.olat.course.groupsandrights.CourseGroupManager#deleteCourseGroupmanagement() */ diff --git a/src/main/java/org/olat/course/nodes/projectbroker/ProjectBrokerCourseEditorController.java b/src/main/java/org/olat/course/nodes/projectbroker/ProjectBrokerCourseEditorController.java index 3bbbf7cfefbab7d6e6f1b96142b5d5715fd51bee..09110164db0c3eaa10583ce521c408c1a033a1b1 100644 --- a/src/main/java/org/olat/course/nodes/projectbroker/ProjectBrokerCourseEditorController.java +++ b/src/main/java/org/olat/course/nodes/projectbroker/ProjectBrokerCourseEditorController.java @@ -336,7 +336,7 @@ public class ProjectBrokerCourseEditorController extends ActivateableTabbableDef getLogger().debug("NODECONFIG_CHANGED_node.shortTitle=" + node.getShortTitle()); String groupName = translate("account.manager.groupname", node.getShortTitle()); String groupDescription = translate("account.manager.groupdescription", node.getShortTitle()); - ProjectBrokerManagerFactory.getProjectGroupManager().updateAccountManagerGroupName(groupName,groupDescription,accountManagerGroup); + accountManagerGroup = ProjectBrokerManagerFactory.getProjectGroupManager().updateAccountManagerGroupName(groupName,groupDescription,accountManagerGroup); } else if (source == dropboxForm) { if (event == Event.CANCELLED_EVENT) { return; diff --git a/src/main/java/org/olat/course/nodes/projectbroker/datamodel/ProjectImpl.java b/src/main/java/org/olat/course/nodes/projectbroker/datamodel/ProjectImpl.java index 63b63b7001143bc6ecfe654ab1b89ccc91ac9d54..e4e4863d3605cd42628cea2e5fde55f46bf13bd8 100644 --- a/src/main/java/org/olat/course/nodes/projectbroker/datamodel/ProjectImpl.java +++ b/src/main/java/org/olat/course/nodes/projectbroker/datamodel/ProjectImpl.java @@ -47,6 +47,11 @@ import org.olat.group.BusinessGroup; */ public class ProjectImpl extends PersistentObject implements Project { + /** + * + */ + private static final long serialVersionUID = 1L; + private static final String CUSTOMFIELD_KEY = "customfield_"; private static final String EVENT_START = "event_start"; @@ -214,10 +219,27 @@ public class ProjectImpl extends PersistentObject implements Project { this.projectBroker = projectBroker; } - + @Override public String toString() { return "Project [title=" + getTitle() + ", description=" + getDescription() + ", state=" + getState() + "] " + super.toString(); } + + @Override + public int hashCode() { + return getKey() == null ? 82301 : getKey().hashCode(); + } + + @Override + public boolean equals(Object obj) { + if(this == obj) { + return true; + } + if(obj instanceof Project) { + Project project = (Project)obj; + return getKey() != null && getKey().equals(project.getKey()); + } + return false; + } public void setAttachedFileName(String attachmentFileName) { this.attachmentFileName = attachmentFileName; diff --git a/src/main/java/org/olat/course/nodes/projectbroker/service/ProjectBrokerManagerImpl.java b/src/main/java/org/olat/course/nodes/projectbroker/service/ProjectBrokerManagerImpl.java index 6f2e0555317a92270fcab4d8df503eeb986eb2a2..0ee7321dfa90cd49e8959b263825763a9de9fde7 100644 --- a/src/main/java/org/olat/course/nodes/projectbroker/service/ProjectBrokerManagerImpl.java +++ b/src/main/java/org/olat/course/nodes/projectbroker/service/ProjectBrokerManagerImpl.java @@ -504,9 +504,13 @@ public class ProjectBrokerManagerImpl extends BasicManager implements ProjectBro ProjectBroker projectBroker = (ProjectBroker)projectCache.get(projectBrokerId.toString()); if (projectBroker == null) { logDebug("find no projectBroker in the cache => create a new one projectBrokerId=" + projectBrokerId); - List projectList = DBFactory.getInstance().find( - "select project from org.olat.course.nodes.projectbroker.datamodel.ProjectImpl as project" + - " where project.projectBroker.key = ?", projectBrokerId, StandardBasicTypes.LONG); + StringBuilder sb = new StringBuilder(); + sb.append("select distinct project from ").append(ProjectImpl.class.getName()).append(" as project ") + .append(" where project.projectBroker.key=:projectBrokerKey"); + + List<Project> projectList = DBFactory.getInstance().getCurrentEntityManager().createQuery(sb.toString(), Project.class) + .setParameter("projectBrokerKey", projectBrokerId) + .getResultList(); projectBroker = getProjectBroker(projectBrokerId); projectBroker.setProjects(projectList); projectCache.put(projectBrokerId.toString(), projectBroker); diff --git a/src/main/java/org/olat/course/nodes/projectbroker/service/ProjectGroupManager.java b/src/main/java/org/olat/course/nodes/projectbroker/service/ProjectGroupManager.java index bed9ff50b868b541b87c8f2c6851ac2ac57c3844..8d20e1f71ca8e0428b7b3f0e58fdd375c48e153f 100644 --- a/src/main/java/org/olat/course/nodes/projectbroker/service/ProjectGroupManager.java +++ b/src/main/java/org/olat/course/nodes/projectbroker/service/ProjectGroupManager.java @@ -79,7 +79,7 @@ public interface ProjectGroupManager { * @param groupDescription * @param accountManagerGroup */ - public abstract void updateAccountManagerGroupName(String groupName, String groupDescription, BusinessGroup accountManagerGroup); + public BusinessGroup updateAccountManagerGroupName(String groupName, String groupDescription, BusinessGroup accountManagerGroup); //////////////////////////// // PROJECT GROUP MANAGEMENT @@ -110,7 +110,7 @@ public interface ProjectGroupManager { * @param initialGroupName New group-name, if the group name already exists, append a number e.g. ' _2' for uniqueness * @param groupDescription New description of group */ - public abstract void changeProjectGroupName(BusinessGroup projectGroup, String initialGroupName, String groupDescription, OLATResource courseResource); + public BusinessGroup changeProjectGroupName(BusinessGroup projectGroup, String initialGroupName, String groupDescription, OLATResource courseResource); /** * Accept candidates as participants, move identity from candidate-group to participant-group @@ -195,7 +195,7 @@ public interface ProjectGroupManager { * @param projectGroup * @param maxMembers */ - public void setProjectGroupMaxMembers(BusinessGroup projectGroup, int maxMembers ); + public BusinessGroup setProjectGroupMaxMembers(BusinessGroup projectGroup, int maxMembers ); /** * Returns true when candidate-list is empty. diff --git a/src/main/java/org/olat/course/nodes/projectbroker/service/ProjectGroupManagerImpl.java b/src/main/java/org/olat/course/nodes/projectbroker/service/ProjectGroupManagerImpl.java index ad4e46720a642020be0291f97b0ae623329e13b4..3a7cc4567fa8848590e1357729f37d4505372c94 100644 --- a/src/main/java/org/olat/course/nodes/projectbroker/service/ProjectGroupManagerImpl.java +++ b/src/main/java/org/olat/course/nodes/projectbroker/service/ProjectGroupManagerImpl.java @@ -151,15 +151,16 @@ public class ProjectGroupManagerImpl extends BasicManager implements ProjectGrou } } - public void updateAccountManagerGroupName(String groupName, String groupDescription, BusinessGroup accountManagerGroup) { + public BusinessGroup updateAccountManagerGroupName(String groupName, String groupDescription, BusinessGroup accountManagerGroup) { // group could have been deleted, see FXOLAT-295 if (accountManagerGroup != null){ BusinessGroupService bgs = CoreSpringFactory.getImpl(BusinessGroupService.class); BusinessGroup reloadedBusinessGroup = bgs.loadBusinessGroup(accountManagerGroup); reloadedBusinessGroup.setName(groupName); reloadedBusinessGroup.setDescription(groupDescription); - bgs.updateBusinessGroup(reloadedBusinessGroup); + return bgs.mergeBusinessGroup(reloadedBusinessGroup); } + return null; } @@ -197,7 +198,7 @@ public class ProjectGroupManagerImpl extends BasicManager implements ProjectGrou * If the goup-name already exist, it will be automatically try another one with suffix e.g. ' _2' * @see org.olat.course.nodes.projectbroker.service.ProjectGroupManager#changeProjectGroupName(org.olat.group.BusinessGroup, java.lang.String, java.lang.String) */ - public void changeProjectGroupName(BusinessGroup projectGroup, String initialGroupName, String groupDescription, OLATResource courseResource) { + public BusinessGroup changeProjectGroupName(BusinessGroup projectGroup, String initialGroupName, String groupDescription, OLATResource courseResource) { BusinessGroupService bgs = CoreSpringFactory.getImpl(BusinessGroupService.class); BusinessGroup reloadedBusinessGroup = bgs.loadBusinessGroup(projectGroup); logDebug("initialGroupName=" + initialGroupName); @@ -216,7 +217,7 @@ public class ProjectGroupManagerImpl extends BasicManager implements ProjectGrou logDebug("groupName=" + groupName); reloadedBusinessGroup.setName(groupName); reloadedBusinessGroup.setDescription(groupDescription); - bgs.updateBusinessGroup(reloadedBusinessGroup); + return bgs.mergeBusinessGroup(reloadedBusinessGroup); } public List<Identity> addCandidates(final List<Identity> addIdentities, final Project project) { @@ -315,12 +316,12 @@ public class ProjectGroupManagerImpl extends BasicManager implements ProjectGrou return BaseSecurityManager.getInstance().isIdentityInSecurityGroup(identity, project.getCandidateGroup()); } - public void setProjectGroupMaxMembers(BusinessGroup projectGroup, int maxMembers ) { + public BusinessGroup setProjectGroupMaxMembers(BusinessGroup projectGroup, int maxMembers ) { BusinessGroupService bgs = CoreSpringFactory.getImpl(BusinessGroupService.class); BusinessGroup reloadedBusinessGroup = bgs.loadBusinessGroup(projectGroup); logDebug("ProjectGroup.name=" + reloadedBusinessGroup.getName() + " setMaxParticipants=" + maxMembers); reloadedBusinessGroup.setMaxParticipants(maxMembers); - bgs.updateBusinessGroup(reloadedBusinessGroup); + return bgs.mergeBusinessGroup(reloadedBusinessGroup); } /////////////////// diff --git a/src/main/java/org/olat/course/run/preview/PreviewCourseGroupManager.java b/src/main/java/org/olat/course/run/preview/PreviewCourseGroupManager.java index 2920af689f4b534fed8b47474b4a283f6199dd25..f5a6307df56f333a49afd2fb67eea20c4d5da9fa 100644 --- a/src/main/java/org/olat/course/run/preview/PreviewCourseGroupManager.java +++ b/src/main/java/org/olat/course/run/preview/PreviewCourseGroupManager.java @@ -86,7 +86,7 @@ final class PreviewCourseGroupManager extends BasicManager implements CourseGrou /** * @see org.olat.course.groupsandrights.CourseGroupManager#isIdentityInLearningGroup(org.olat.core.id.Identity, java.lang.String) */ - public boolean isIdentityInLearningGroup(Identity identity, String groupName) { + public boolean isIdentityInGroup(Identity identity, String groupName) { return groups.contains(groupName); } @@ -97,13 +97,6 @@ final class PreviewCourseGroupManager extends BasicManager implements CourseGrou return groups.contains(groupName); } - /** - * @see org.olat.course.groupsandrights.CourseGroupManager#isIdentityInRightGroup(org.olat.core.id.Identity, java.lang.String) - */ - public boolean isIdentityInRightGroup(Identity identity, String groupName) { - return groups.contains(groupName); - } - /** * @see org.olat.course.groupsandrights.CourseGroupManager#isIdentityInLearningArea(org.olat.core.id.Identity, java.lang.String) */ @@ -130,17 +123,10 @@ final class PreviewCourseGroupManager extends BasicManager implements CourseGrou return isCourseAdmin; } - /** - * @see org.olat.course.groupsandrights.CourseGroupManager#isIdentityParticipantInAnyRightGroup(org.olat.core.id.Identity) - */ - public boolean isIdentityParticipantInAnyRightGroup(Identity identity) { - throw new AssertException("unsupported"); - } - /** * @see org.olat.course.groupsandrights.CourseGroupManager#isIdentityParticipantInAnyLearningGroup(org.olat.core.id.Identity) */ - public boolean isIdentityParticipantInAnyLearningGroup(Identity identity) { + public boolean isIdentityParticipantInAnyGroup(Identity identity) { throw new AssertException("unsupported"); } diff --git a/src/main/java/org/olat/group/BusinessGroupFactory.java b/src/main/java/org/olat/group/BusinessGroupFactory.java index ee194f21f502f5359814fe4bdb3ce6a4f82b93a2..f284269d596d82f6b769ce583bb1bd42a00644fb 100644 --- a/src/main/java/org/olat/group/BusinessGroupFactory.java +++ b/src/main/java/org/olat/group/BusinessGroupFactory.java @@ -25,23 +25,16 @@ package org.olat.group; -import java.util.Set; - import org.olat.basesecurity.BaseSecurity; import org.olat.basesecurity.BaseSecurityManager; import org.olat.basesecurity.Constants; import org.olat.basesecurity.SecurityGroup; -import org.olat.core.commons.persistence.DB; import org.olat.core.commons.persistence.DBFactory; -import org.olat.core.commons.persistence.DBQuery; import org.olat.core.id.Identity; -import org.olat.core.logging.AssertException; import org.olat.core.logging.Tracing; -import org.olat.group.context.BGContext; import org.olat.group.properties.BusinessGroupPropertyManager; import org.olat.resource.OLATResource; import org.olat.resource.OLATResourceManager; -import org.olat.testutils.codepoints.server.Codepoint; /** * Description: <BR/> Use the business group factory to create new instances of @@ -151,7 +144,7 @@ public class BusinessGroupFactory { * @param groupContext * @return the group or null if the groupname is not unique in the given * context - */ + *//* private static BusinessGroup createAndPersistLearningGroup(Identity identity, String name, String description, Integer minParticipants, Integer maxParticipants, Boolean waitingListEnabled,Boolean autoCloseRanksEnabled, BGContext groupContext) { /* @@ -160,7 +153,7 @@ public class BusinessGroupFactory { * security groups...................................................... [3] * create 2 policies, ownerGroup -> PERMISSION_ACCESS ....partipiciantGroup -> * PERMISSION_READ - */ + *//* BusinessGroupImpl businessgroup = null; BaseSecurity securityManager = BaseSecurityManager.getInstance(); @@ -192,7 +185,7 @@ public class BusinessGroupFactory { * policies: - ownerGroup can do everything on this businessgroup -> is an * admin, can invite people to owner.- & partipiciantgroup - * partipiciantGroup can read this businessgroup - */ + *//* OLATResource businessgroupOlatResource = OLATResourceManager.getInstance().createOLATResourceInstance(businessgroup); OLATResourceManager.getInstance().saveOLATResource(businessgroupOlatResource); OLATResource groupContextOlatResource = OLATResourceManager.getInstance().findResourceable(groupContext); @@ -215,7 +208,7 @@ public class BusinessGroupFactory { BusinessGroupPropertyManager bgpm = new BusinessGroupPropertyManager(businessgroup); bgpm.createAndPersistDisplayMembers(true, false, false); return businessgroup; - } + }*/ /** * Create a group of type right group @@ -226,7 +219,7 @@ public class BusinessGroupFactory { * @param groupContext * @return the group or null if the groupname is not unique in the given * context - */ + *//* private static BusinessGroup createAndPersistRightGroup(Identity identity, String name, String description, Integer minParticipants, Integer maxParticipants, BGContext groupContext) { /* @@ -234,7 +227,7 @@ public class BusinessGroupFactory { * learningGroup with name, description, introMsg and the security * group...................................................... [3] create 2 * policies, partipiciantGroup -> PERMISSION_READ - */ + *//* BusinessGroupImpl businessgroup = null; BaseSecurity securityManager = BaseSecurityManager.getInstance(); @@ -249,7 +242,7 @@ public class BusinessGroupFactory { // group SecurityGroup partipiciantGroup = securityManager.createAndPersistSecurityGroup(); // - businessgroup = new BusinessGroupImpl(BusinessGroup.TYPE_RIGHTGROUP, name, description, null, partipiciantGroup,null/* no waitingGroup */); + businessgroup = new BusinessGroupImpl(BusinessGroup.TYPE_RIGHTGROUP, name, description, null, partipiciantGroup,null/* no waitingGroup *//*); businessgroup.setMinParticipants(minParticipants); businessgroup.setMaxParticipants(maxParticipants); // @@ -259,7 +252,7 @@ public class BusinessGroupFactory { } /* * policies: - partipiciantGroup can read this businessgroup - */ + *//* OLATResource businessgroupOlatResource = OLATResourceManager.getInstance().createOLATResourceInstance(businessgroup); OLATResourceManager.getInstance().saveOLATResource(businessgroupOlatResource); securityManager.createAndPersistPolicyWithResource(partipiciantGroup, Constants.PERMISSION_READ, businessgroupOlatResource); @@ -282,7 +275,7 @@ public class BusinessGroupFactory { * @param type * @param groupContext * @return - */ + *//* private static boolean checkIfOneOrMoreNameExistsInContext(Set names, BGContext groupContext) { DB db = DBFactory.getInstance(); String query = "select count(bgs) from " @@ -306,7 +299,7 @@ public class BusinessGroupFactory { * @param groupContext The group context of null * @return true if a group in such a context with the given name exists false * otherwhise - */ + *//* private static boolean testIfGroupAlreadyExists(String name, String type, BGContext groupContext) { DB db = DBFactory.getInstance(); String query = "select count(bgs) from " + " org.olat.group.BusinessGroupImpl as bgs " + " where bgs.type = :type" @@ -318,5 +311,5 @@ public class BusinessGroupFactory { int result = ((Long) dbq.list().get(0)).intValue(); if (result != 0) return true; return false; - } + }*/ } \ No newline at end of file diff --git a/src/main/java/org/olat/group/BusinessGroupManagerImpl.java b/src/main/java/org/olat/group/BusinessGroupManagerImpl.java index 2103fa1e31e73cd5d5037b671d998e4904d5be58..5d2b860ade267c5d4172a012e7288c7792d267aa 100644 --- a/src/main/java/org/olat/group/BusinessGroupManagerImpl.java +++ b/src/main/java/org/olat/group/BusinessGroupManagerImpl.java @@ -107,7 +107,7 @@ import org.olat.util.logging.activity.LoggingResourceable; * * @author patrick */ -public class BusinessGroupManagerImpl extends BasicManager implements BusinessGroupManager, UserDataDeletable { +public class BusinessGroupManagerImpl extends BasicManager implements BusinessGroupManager /*, UserDataDeletable */ { private static BusinessGroupManager INSTANCE; @@ -119,20 +119,20 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr /** * @return singleton instance - */ + *//* public static BusinessGroupManager getInstance() { return INSTANCE; - } + }*/ /** * [used by spring] - */ + *//* private BusinessGroupManagerImpl(BaseSecurity securityManager, UserDeletionManager userDeletionManager) { userDeletionManager.registerDeletableUserData(this); this.securityManager = securityManager; deleteListeners = new ArrayList<DeletableGroupData>(); INSTANCE = this; - } + }*/ /** * [used by Spring] @@ -162,15 +162,15 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr * @param names * @param groupContext * @return - */ + *//* protected boolean checkIfOneOrMoreNameExistsInContext(Set<String> names, BGContext groupContext){ return CoreSpringFactory.getImpl(BusinessGroupService.class).checkIfOneOrMoreNameExistsInContext(names, null); - } + }*/ /** * @see org.olat.group.BusinessGroupManager#findBusinessGroupsOwnedBy(java.lang.String, * org.olat.core.id.Identity, org.olat.group.context.BGContext) - */ + *//* public List<BusinessGroup> findBusinessGroupsOwnedBy(String type, Identity identityP, BGContext bgContext) { // attach group context to session - maybe a proxy... String query = "select bgi from " + " org.olat.basesecurity.SecurityGroupMembershipImpl as sgmi," @@ -180,13 +180,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr DB db = DBFactory.getInstance(); DBQuery dbq = db.createQuery(query); - /* - * query.append("select distinct v from" + " - * org.olat.basesecurity.SecurityGroupMembershipImpl as sgmsi," + " - * org.olat.repository.RepositoryEntry v" + " inner join fetch v.ownerGroup - * as secGroup" + " inner join fetch v.olatResource as res where" + " - * sgmsi.securityGroup = secGroup and sgmsi.identity.key="); - */ + dbq.setLong("identId", identityP.getKey().longValue()); if (bgContext != null) dbq.setEntity("context", bgContext); @@ -194,12 +188,12 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr List<BusinessGroup> res = dbq.list(); return res; - } + }*/ /** * @see org.olat.group.BusinessGroupManager#findBusinessGroupsAttendedBy(java.lang.String, * org.olat.core.id.Identity, org.olat.group.context.BGContext) - */ + *//* public List<BusinessGroup> findBusinessGroupsAttendedBy(String type, Identity identityP, BGContext bgContext) { String query = "select bgi from " + " org.olat.group.BusinessGroupImpl as bgi " + ", org.olat.basesecurity.SecurityGroupMembershipImpl as sgmi" @@ -319,21 +313,21 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr dbq.setParameterList("tools", params.getTools()); } return dbq; - } + }*/ /** * * @see org.olat.group.BusinessGroupManager#getAllBusinessGroups() - */ + *//* public List<BusinessGroup> getAllBusinessGroups() { DBQuery dbq = DBFactory.getInstance().createQuery("select bgi from " + " org.olat.group.BusinessGroupImpl as bgi "); return dbq.list(); - } + }*/ /** * @see org.olat.group.BusinessGroupManager#findBusinessGroupsAttendedBy(java.lang.String, * org.olat.core.id.Identity, org.olat.group.context.BGContext) - */ + *//* public List<BusinessGroup> findBusinessGroupsWithWaitingListAttendedBy(String type, Identity identityP, BGContext bgContext) { String query = "select bgi from " + " org.olat.group.BusinessGroupImpl as bgi " + ", org.olat.basesecurity.SecurityGroupMembershipImpl as sgmi" @@ -349,13 +343,14 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr List<BusinessGroup> res = dbq.list(); return res; - } + }*/ /** * @see org.olat.group.BusinessGroupManager#findBusinessGroupsAttendedBy(java.lang.String, * org.olat.core.id.Identity, org.olat.group.context.BGContext) */ //fxdiff VCRP-1,2: access control of resources + /* public List<BusinessGroup> findBusinessGroups(Collection<String> types, Identity identityP34, Long id, String name, String description, String owner) { StringBuilder sb = new StringBuilder(); sb.append("select distinct(bgi) from ").append(BusinessGroupImpl.class.getName()).append(" as bgi"); @@ -463,11 +458,11 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr // To test for literal instances of '_', we have to escape it. string = string.replace("_", "\\_"); return string.toLowerCase(); - } + }*/ /** * @see org.olat.group.BusinessGroupManager#findBusinessGroup(org.olat.basesecurity.SecurityGroup) - */ + *//* public BusinessGroup findBusinessGroup(SecurityGroup secGroup) { StringBuilder sb = new StringBuilder(); sb.append("select bgi from ").append(BusinessGroupImpl.class.getName()).append(" as bgi where ") @@ -478,19 +473,19 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr List<BusinessGroup> res = query.list(); if(res.isEmpty()) return null; return res.get(0); - } + }*/ /** * @see org.olat.group.BusinessGroupManager#updateBusinessGroup(org.olat.group.BusinessGroup) - */ + *//* public void updateBusinessGroup(BusinessGroup updatedBusinessGroup) { updatedBusinessGroup.setLastModified(new Date()); DBFactory.getInstance().updateObject(updatedBusinessGroup); - } + }*/ /** * @see org.olat.group.BusinessGroupManager#deleteBusinessGroup(org.olat.group.BusinessGroup) - */ + *//* public void deleteBusinessGroup(BusinessGroup businessGroupTodelete) { try{ OLATResourceableJustBeforeDeletedEvent delEv = new OLATResourceableJustBeforeDeletedEvent(businessGroupTodelete); @@ -566,7 +561,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr //TODO gm private void removeFromRepositoryEntrySecurityGroup(BusinessGroup group) { - /* + *//* BGContext context = group.getGroupContext(); if(context == null) return;//nothing to do @@ -599,13 +594,13 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr } } } - */ - } + + }*/ /** * @see org.olat.group.BusinessGroupManager#deleteBusinessGroupWithMail(org.olat.group.BusinessGroup, * org.olat.core.gui.control.WindowControl, org.olat.core.gui.UserRequest, * org.olat.core.gui.translator.Translator, java.util.List) - */ + *//* public void deleteBusinessGroupWithMail(BusinessGroup businessGroupTodelete, WindowControl wControl, UserRequest ureq, Translator trans, List contactLi) { Codepoint.codepoint(this.getClass(), "deleteBusinessGroupWithMail"); @@ -640,23 +635,23 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr MailHelper.printErrorsAndWarnings(mailerResult, wControl, ureq.getLocale()); } - } + }*/ /** * @see org.olat.group.BusinessGroupManager#deleteBusinessGroups(java.util.List) - */ + *//* public void deleteBusinessGroups(List businessGroups) { Iterator iterator = businessGroups.iterator(); while (iterator.hasNext()) { BusinessGroup group = (BusinessGroup) iterator.next(); deleteBusinessGroup(group); } - } + }*/ /** * @see org.olat.group.BusinessGroupManager#isIdentityInBusinessGroup(org.olat.core.id.Identity, * java.lang.String, org.olat.group.context.BGContext) - */ + *//* public boolean isIdentityInBusinessGroup(Identity identity, String groupName, BGContext groupContext) { DB db = DBFactory.getInstance(); StringBuilder q = new StringBuilder(); @@ -677,12 +672,12 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr List result = query.list(); if (result.size() == 0) return false; return ( ((Long) result.get(0)).intValue() > 0); - } + }*/ /** * @see org.olat.group.BusinessGroupManager#isIdentityInBusinessGroup(org.olat.core.id.Identity, * org.olat.group.BusinessGroup) - */ + *//* public boolean isIdentityInBusinessGroup(Identity identity, BusinessGroup businessGroup) { SecurityGroup participants = businessGroup.getPartipiciantGroup(); SecurityGroup owners = businessGroup.getOwnerGroup(); @@ -751,19 +746,19 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr DBQuery dbq = db.createQuery(query.toString()); dbq.setLong("identKey", identity.getKey()); return dbq; - } + }*/ /** * @see org.olat.group.BusinessGroupManager#loadBusinessGroup(org.olat.group.BusinessGroup) - */ + *//* public BusinessGroup loadBusinessGroup(BusinessGroup currBusinessGroup) { return (BusinessGroup) DBFactory.getInstance().loadObject(currBusinessGroup); - } + }*/ /** * @see org.olat.group.BusinessGroupManager#loadBusinessGroup(java.lang.Long, * boolean) - */ + *//* public BusinessGroup loadBusinessGroup(Long groupKey, boolean strict) { if (strict) return (BusinessGroup) DBFactory.getInstance().loadObject(BusinessGroupImpl.class, groupKey); return (BusinessGroup) DBFactory.getInstance().findObject(BusinessGroupImpl.class, groupKey); @@ -772,23 +767,23 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr public BusinessGroup loadBusinessGroup(String groupKey, boolean strict) { Long key = Long.parseLong(groupKey); return loadBusinessGroup(key, strict); - } + }*/ /** * @see org.olat.group.BusinessGroupManager#loadBusinessGroup(java.lang.Long, * boolean) - */ + *//* //fxdiff VCRP-1,2: access control of resources public BusinessGroup loadBusinessGroup(OLATResource resource, boolean strict) { return loadBusinessGroup(resource.getResourceableId(), strict); - } + }*/ /** * @see org.olat.group.BusinessGroupManager#copyBusinessGroup(org.olat.group.BusinessGroup, * java.lang.String, java.lang.String, java.lang.Integer, * java.lang.Integer, org.olat.group.context.BGContext, java.util.Map, * boolean, boolean, boolean, boolean, boolean, boolean) - */ + *//* public BusinessGroup copyBusinessGroup(BusinessGroup sourceBusinessGroup, String targetName, String targetDescription, Integer targetMin, Integer targetMax, BGContext targetBgContext, Map areaLookupMap, boolean copyAreas, boolean copyCollabToolConfig, boolean copyRights, boolean copyOwners, boolean copyParticipants, boolean copyMemberVisibility, boolean copyWaitingList) { @@ -876,14 +871,14 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr return newGroup; } - +*/ /** * @see org.olat.group.BusinessGroupManager#addParticipant(org.olat.core.gui.control.WindowControl, * org.olat.core.gui.UserRequest, org.olat.core.gui.translator.Translator, * org.olat.core.id.Identity, org.olat.group.BusinessGroup, * org.olat.group.ui.BGConfigFlags, org.olat.core.logging.UserActivityLogger, * boolean) - */ + *//* public void addParticipantAndFireEvent(Identity ureqIdentity, final Identity identity, final BusinessGroup group, BGConfigFlags flags, boolean doOnlyPostAddingStuff) { CoordinatorManager.getInstance().getCoordinator().getSyncer().assertAlreadyDoInSyncFor(group); @@ -908,7 +903,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr // do logging ThreadLocalUserActivityLogger.log(GroupLoggingAction.GROUP_PARTICIPANT_ADDED, getClass(), LoggingResourceable.wrap(group), LoggingResourceable.wrap(identity)); // send notification mail in your controller! - } + }*/ /** * @see org.olat.group.BusinessGroupManager#addOwner(org.olat.core.gui.control.WindowControl, @@ -916,7 +911,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr * org.olat.core.id.Identity, org.olat.group.BusinessGroup, * org.olat.group.ui.BGConfigFlags, org.olat.core.logging.UserActivityLogger, * boolean) - */ + *//* public void addOwnerAndFireEvent(Identity ureqIdentity, Identity identity, BusinessGroup group, BGConfigFlags flags, boolean doOnlyPostAddingStuff) { if (!doOnlyPostAddingStuff) { @@ -965,7 +960,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr //remove subsciptions if user gets removed //TODO removeSubscriptions(identity, group); - } + }*/ /** * @see org.olat.group.BusinessGroupManager#removeOwner(org.olat.core.gui.control.WindowControl, @@ -973,7 +968,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr * org.olat.core.id.Identity, org.olat.group.BusinessGroup, * org.olat.group.ui.BGConfigFlags, org.olat.core.logging.UserActivityLogger, * boolean) - */ + *//* public void removeOwnerAndFireEvent(Identity ureqIdentity, Identity identity, BusinessGroup group, BGConfigFlags flags, boolean doOnlyPostRemovingStuff) { if (!doOnlyPostRemovingStuff) { @@ -1003,7 +998,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr ThreadLocalUserActivityLogger.log(GroupLoggingAction.GROUP_OWNER_REMOVED, getClass(), LoggingResourceable.wrap(group), LoggingResourceable.wrap(identity)); // send notification mail in your controller! - } + }*/ /** * @see org.olat.group.BusinessGroupManager#removeParticipant(org.olat.core.gui.control.WindowControl, @@ -1011,7 +1006,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr * org.olat.core.id.Identity, org.olat.group.BusinessGroup, * org.olat.group.ui.BGConfigFlags, org.olat.core.logging.UserActivityLogger, * boolean) - */ + *//* public void removeParticipantAndFireEvent(final Identity ureqIdentity, final Identity identity, final BusinessGroup group, final BGConfigFlags flags, final boolean doOnlyPostRemovingStuff) { CoordinatorManager.getInstance().getCoordinator().getSyncer().assertAlreadyDoInSyncFor(group); @@ -1041,7 +1036,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr transferFirstIdentityFromWaitingToParticipant(ureqIdentity, group, flags); } // send notification mail in your controller! - } + }*/ /** * @see org.olat.group.BusinessGroupManager#addParticipant(org.olat.core.gui.control.WindowControl, @@ -1049,7 +1044,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr * org.olat.core.id.Identity, org.olat.group.BusinessGroup, * org.olat.group.ui.BGConfigFlags, org.olat.core.logging.UserActivityLogger, * boolean) - */ + *//* public void addToWaitingListAndFireEvent(Identity ureqIdentity, final Identity identity, final BusinessGroup group, boolean doOnlyPostAddingStuff) { CoordinatorManager.getInstance().getCoordinator().getSyncer().assertAlreadyDoInSyncFor(group); @@ -1061,7 +1056,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr // do logging ThreadLocalUserActivityLogger.log(GroupLoggingAction.GROUP_TO_WAITING_LIST_ADDED, getClass(), LoggingResourceable.wrap(identity)); // send notification mail in your controller! - } + }*/ /** * @see org.olat.group.BusinessGroupManager#removeFromWaitingListAndFireEvent(org.olat.core.gui.control.WindowControl, @@ -1069,7 +1064,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr * org.olat.core.id.Identity, org.olat.group.BusinessGroup, * org.olat.group.ui.BGConfigFlags, org.olat.core.logging.UserActivityLogger, * boolean) - */ + *//* public void removeFromWaitingListAndFireEvent(Identity userRequestIdentity, final Identity identity, final BusinessGroup group, boolean doOnlyPostRemovingStuff) { CoordinatorManager.getInstance().getCoordinator().getSyncer().assertAlreadyDoInSyncFor(group); @@ -1333,7 +1328,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr /** * * @see org.olat.group.BusinessGroupManager#moveIdenitFromWaitingListToParticipant(org.olat.core.id.Identity, org.olat.core.gui.control.WindowControl, org.olat.core.gui.UserRequest, org.olat.core.gui.translator.Translator, org.olat.group.BusinessGroup, org.olat.group.ui.BGConfigFlags, org.olat.core.logging.UserActivityLogger) - */ + *//* public BusinessGroupAddResponse moveIdenityFromWaitingListToParticipant(final List<Identity> choosenIdentities, final Identity ureqIdentity, final BusinessGroup currBusinessGroup, final BGConfigFlags flags) { final BusinessGroupAddResponse response = new BusinessGroupAddResponse(); CoordinatorManager.getInstance().getCoordinator().getSyncer().doInSync(currBusinessGroup,new SyncerExecutor(){ @@ -1357,7 +1352,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr /** * * @see org.olat.group.BusinessGroupManager#getPositionInWaitingListFor(org.olat.core.id.Identity, org.olat.group.BusinessGroup) - */ + *//* public int getPositionInWaitingListFor(Identity identity, BusinessGroup businessGroup) { // get position in waiting-list List identities = securityManager.getIdentitiesAndDateOfSecurityGroup(businessGroup.getWaitingGroup(),true); @@ -1398,7 +1393,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr /** * * @see org.olat.group.BusinessGroupManager#addOwnersAndFireEvent(org.olat.core.id.Identity, java.util.List, org.olat.group.BusinessGroup, org.olat.group.ui.BGConfigFlags, org.olat.core.logging.UserActivityLogger) - */ + *//* public BusinessGroupAddResponse addOwnersAndFireEvent(Identity ureqIdentity, List<Identity> addIdentities, BusinessGroup currBusinessGroup, BGConfigFlags flags) { BusinessGroupAddResponse response = new BusinessGroupAddResponse(); for (Identity identity : addIdentities) { @@ -1424,7 +1419,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr /** * * @see org.olat.group.BusinessGroupManager#addParticipantsAndFireEvent(org.olat.core.id.Identity, java.util.List, org.olat.group.BusinessGroup, org.olat.group.ui.BGConfigFlags, org.olat.core.logging.UserActivityLogger) - */ + *//* public BusinessGroupAddResponse addParticipantsAndFireEvent(final Identity ureqIdentity, final List<Identity> addIdentities, BusinessGroup acurrBusinessGroup, final BGConfigFlags flags) { final BusinessGroupAddResponse response = new BusinessGroupAddResponse(); final BusinessGroup currBusinessGroup = loadBusinessGroup(acurrBusinessGroup); // reload business group @@ -1453,7 +1448,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr /** * * @see org.olat.group.BusinessGroupManager#addToWaitingListAndFireEvent(org.olat.core.id.Identity, java.util.List, org.olat.group.BusinessGroup, org.olat.group.ui.BGConfigFlags, org.olat.core.logging.UserActivityLogger) - */ + *//* public BusinessGroupAddResponse addToWaitingListAndFireEvent(final Identity ureqIdentity, final List<Identity> addIdentities, BusinessGroup acurrBusinessGroup, BGConfigFlags flags) { final BusinessGroupAddResponse response = new BusinessGroupAddResponse(); final BusinessGroup currBusinessGroup = loadBusinessGroup(acurrBusinessGroup); // reload business group @@ -1490,7 +1485,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr /** * * @see org.olat.group.BusinessGroupManager#removeOwnersAndFireEvent(org.olat.core.id.Identity, java.util.List, org.olat.group.BusinessGroup, org.olat.group.ui.BGConfigFlags, org.olat.core.logging.UserActivityLogger) - */ + *//* public void removeOwnersAndFireEvent(Identity ureqIdentity, List<Identity> identities, BusinessGroup currBusinessGroup, BGConfigFlags flags) { for (Identity identity : identities) { removeOwnerAndFireEvent(ureqIdentity, identity, currBusinessGroup, flags, false); @@ -1501,7 +1496,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr /** * * @see org.olat.group.BusinessGroupManager#removeParticipantsAndFireEvent(org.olat.core.gui.control.WindowControl, org.olat.core.id.Identity, org.olat.core.gui.translator.Translator, java.util.List, org.olat.group.BusinessGroup, org.olat.group.ui.BGConfigFlags, org.olat.core.logging.UserActivityLogger) - */ + *//* public void removeParticipantsAndFireEvent(final Identity ureqIdentity, final List<Identity> identities, final BusinessGroup currBusinessGroup, final BGConfigFlags flags) { CoordinatorManager.getInstance().getCoordinator().getSyncer().doInSync(currBusinessGroup, new SyncerExecutor(){ public void execute() { @@ -1516,7 +1511,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr /** * * @see org.olat.group.BusinessGroupManager#removeFromWaitingListAndFireEvent(org.olat.core.id.Identity, org.olat.core.gui.translator.Translator, java.util.List, org.olat.group.BusinessGroup, org.olat.group.ui.BGConfigFlags, org.olat.core.logging.UserActivityLogger) - */ + *//* public void removeFromWaitingListAndFireEvent(final Identity ureqIdentity, final List<Identity> identities, final BusinessGroup currBusinessGroup, final BGConfigFlags flags) { CoordinatorManager.getInstance().getCoordinator().getSyncer().doInSync(currBusinessGroup, new SyncerExecutor(){ public void execute() { @@ -1575,7 +1570,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr * @param flags * @param logger * @param secMgr - */ + *//* //o_clusterOK by:cg call this method only from synchronized code-block (removeParticipantAndFireEvent( ). private void transferFirstIdentityFromWaitingToParticipant(Identity ureqIdentity, BusinessGroup group, BGConfigFlags flags) { CoordinatorManager.getInstance().getCoordinator().getSyncer().assertAlreadyDoInSyncFor(group); @@ -1586,7 +1581,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr int waitingPartipiciantSize = securityManager.countIdentitiesOfSecurityGroup(group.getPartipiciantGroup()); if ( (maxSize != null) && (waitingPartipiciantSize < maxSize.intValue()) ) { // ok it has free places => get first idenity from Waitinglist - List identities = securityManager.getIdentitiesAndDateOfSecurityGroup(group.getWaitingGroup(), true/*sortedByAddedDate*/); + List identities = securityManager.getIdentitiesAndDateOfSecurityGroup(group.getWaitingGroup(), true/*sortedByAddedDate*//*); int i = 0; boolean transferNotDone = true; while (i<identities.size() && transferNotDone) { @@ -1634,7 +1629,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr * If there is no other owner for a group, the olat-administrator (defined in spring config) will be added as owner. * * @see org.olat.user.UserDataDeletable#deleteUserData(org.olat.core.id.Identity) - */ + *//* public void deleteUserData(Identity identity, String newDeletedUserName) { // remove as Participant List<BusinessGroup> attendedGroups = findAllBusinessGroupsAttendedBy(identity); @@ -1679,7 +1674,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr public void archiveGroups(BGContext context, File exportFile) { BusinessGroupArchiver.getInstance().archiveBGContext(null, exportFile); } - */ + *//* private void removeSubscriptions(Identity identity, BusinessGroup group) { NotificationsManager notiMgr = NotificationsManager.getInstance(); @@ -1696,7 +1691,7 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr /** * @see org.olat.group.BusinessGroupManager#setLastUsageFor(org.olat.group.BusinessGroup) - */ + *//* public BusinessGroup setLastUsageFor(final BusinessGroup currBusinessGroup) { //o_clusterOK by:cg return CoordinatorManager.getInstance().getCoordinator().getSyncer().doInSync(currBusinessGroup, new SyncerCallback<BusinessGroup>() { @@ -1720,11 +1715,12 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr } } }); - } + }*/ /** * @see org.olat.group.BusinessGroupManager#createUniqueBusinessGroupsFor(java.util.Set, org.olat.group.context.BGContext, java.lang.String, java.lang.Integer, java.lang.Integer, java.lang.Boolean, java.lang.Boolean) */ + /* public Set<BusinessGroup> createUniqueBusinessGroupsFor(final Set<String> allNames, final BGContext bgContext, final String bgDesc, final Integer bgMin, final Integer bgMax, final Boolean enableWaitinglist, final Boolean enableAutoCloseRanks) { //o_clusterOK by:cg @@ -1777,6 +1773,6 @@ public class BusinessGroupManagerImpl extends BasicManager implements BusinessGr List<BusinessGroup> res = dbq.list(); return res; - } + }*/ } diff --git a/src/main/java/org/olat/group/BusinessGroupModule.java b/src/main/java/org/olat/group/BusinessGroupModule.java index b5b22d5284377b53f820a4484c0220dfb63c9ddb..22220d1733c3b5d07ef9076a78e4277c1d14347b 100644 --- a/src/main/java/org/olat/group/BusinessGroupModule.java +++ b/src/main/java/org/olat/group/BusinessGroupModule.java @@ -39,6 +39,11 @@ public class BusinessGroupModule extends AbstractOLATModule { public static String ORES_TYPE_GROUP = OresHelper.calculateTypeName(BusinessGroup.class); + public static final String LAST_USAGE_DURATION_PROPERTY_NAME = "LastUsageDuration"; + public static final int DEFAULT_LAST_USAGE_DURATION = 24; + public static final String DELETE_EMAIL_DURATION_PROPERTY_NAME = "DeleteEmailDuration"; + public static final int DEFAULT_DELETE_EMAIL_DURATION = 30; + /** * [used by spring] */ @@ -78,5 +83,21 @@ public class BusinessGroupModule extends AbstractOLATModule { public void setPersistedProperties(PersistedProperties persistedProperties) { this.moduleConfigProperties = persistedProperties; } + + public void setLastUsageDuration(int lastUsageDuration) { + setIntProperty(LAST_USAGE_DURATION_PROPERTY_NAME, lastUsageDuration, true); + } + + public void setDeleteEmailDuration(int deleteEmailDuration) { + setIntProperty(DELETE_EMAIL_DURATION_PROPERTY_NAME, deleteEmailDuration, true); + } + + public int getLastUsageDuration() { + return DEFAULT_LAST_USAGE_DURATION;// getIntProperty(LAST_USAGE_DURATION_PROPERTY_NAME, DEFAULT_LAST_USAGE_DURATION); + } + + public int getDeleteEmailDuration() { + return DEFAULT_DELETE_EMAIL_DURATION;//getIntProperty(DELETE_EMAIL_DURATION_PROPERTY_NAME, DEFAULT_DELETE_EMAIL_DURATION); + } } diff --git a/src/main/java/org/olat/group/BusinessGroupService.java b/src/main/java/org/olat/group/BusinessGroupService.java index 74b00c3b9338ff4ccc257c82ced6aaac45dd6ca1..0d0d77951f399ca013ad293ed0b4478b074131bc 100644 --- a/src/main/java/org/olat/group/BusinessGroupService.java +++ b/src/main/java/org/olat/group/BusinessGroupService.java @@ -26,11 +26,13 @@ import java.util.Locale; import java.util.Map; import java.util.Set; -import org.olat.admin.user.groups.AddToGroupsEvent; import org.olat.basesecurity.SecurityGroup; +import org.olat.core.gui.translator.Translator; import org.olat.core.id.Identity; +import org.olat.core.util.mail.MailTemplate; import org.olat.core.util.mail.MailerResult; import org.olat.group.area.BGArea; +import org.olat.group.model.AddToGroupsEvent; import org.olat.group.model.SearchBusinessGroupParams; import org.olat.group.ui.BGConfigFlags; import org.olat.repository.RepositoryEntry; @@ -61,12 +63,21 @@ public interface BusinessGroupService { public BusinessGroup mergeBusinessGroup(BusinessGroup group); - public void updateBusinessGroup(BusinessGroup group); - public void deleteBusinessGroup(BusinessGroup group); + public void deleteGroupsAfterLifeCycle(List<BusinessGroup> groups); + + public List<BusinessGroup> getDeletableGroups(int lastLoginDuration); + + public List<BusinessGroup> getGroupsInDeletionProcess(int deleteEmailDuration); + + public List<BusinessGroup> getGroupsReadyToDelete(int deleteEmailDuration); + public MailerResult deleteBusinessGroupWithMail(BusinessGroup group, String businessPath, Identity deletedBy, Locale locale); + public String sendDeleteEmailTo(List<BusinessGroup> selectedGroups, MailTemplate mailTemplate, boolean isTemplateChanged, String keyEmailSubject, + String keyEmailBody, Identity sender, Translator pT); + public BusinessGroup setLastUsageFor(BusinessGroup group); public BusinessGroup loadBusinessGroup(BusinessGroup group); @@ -156,7 +167,7 @@ public interface BusinessGroupService { public String[] addIdentityToGroups(AddToGroupsEvent groupsEv, final Identity ident, final Identity addingIdentity); - public String[] addIdentityToGroups(List<Long> ownGroups, List<Long> partGroups, List<Long> mailGroups, final Identity ident, final Identity addingIdentity); + //public String[] addIdentityToGroups(List<Long> ownGroups, List<Long> partGroups, List<Long> mailGroups, final Identity ident, final Identity addingIdentity); //security public boolean isIdentityInBusinessGroup(Identity identity, BusinessGroup businessGroup); @@ -184,10 +195,6 @@ public interface BusinessGroupService { public void importGroups(OLATResource resource, File fGroupExportXML); public void archiveGroups(List<BusinessGroup> groups, File exportFile); - - //TODO move to area service - public File archiveAreaMembers(OLATResource resource, List<String> columnList, List<BGArea> areaList, String archiveType, - Locale locale, String charset); public File archiveGroupMembers(OLATResource resource, List<String> columnList, List<BusinessGroup> groupList, String archiveType, Locale locale, String charset); diff --git a/src/main/java/org/olat/group/_spring/businessGroupContext.xml b/src/main/java/org/olat/group/_spring/businessGroupContext.xml index 33fb565f1beff012aeb0d51495aa26be32330838..7c921eaa4efe5d2b2716c8e47e5b60680c54a5e6 100644 --- a/src/main/java/org/olat/group/_spring/businessGroupContext.xml +++ b/src/main/java/org/olat/group/_spring/businessGroupContext.xml @@ -18,13 +18,13 @@ <bean id="businessGroupModule" class="org.olat.group.BusinessGroupModule" init-method="init" depends-on="userModule"/> + <!-- <bean id="businessGroupManager" class="org.olat.group.BusinessGroupManagerImpl" depends-on="collaborationToolsFactory"> <constructor-arg index="0" ref="baseSecurityManager" /> <constructor-arg index="1" ref="userDeletionManager" /> <property name="dbVendor" value="${db.vendor}" /> </bean> - - <bean id="areaManager" class="org.olat.group.area.BGAreaManagerImpl"/> + --> <bean id="groupDeletionManager" class="org.olat.group.manager.BusinessGroupDeletionManager"> <constructor-arg index="0" ref="deletionModule" /> diff --git a/src/main/java/org/olat/group/area/BGAreaImpl.hbm.xml b/src/main/java/org/olat/group/area/BGAreaImpl.hbm.xml index 15ed601b76efaf41d33b039ae6380fb6e2348631..668df7e66b699fce0484302d666fc933551ca765 100644 --- a/src/main/java/org/olat/group/area/BGAreaImpl.hbm.xml +++ b/src/main/java/org/olat/group/area/BGAreaImpl.hbm.xml @@ -20,7 +20,7 @@ <property name="name" type="string" column="name" not-null="true" unique="false" index="name_idx3"/> <property name="description" column="descr" length="16777210" not-null="false" unique="false" /> - <property name="groupContextKey" column="groupcontext_fk" type="long" /> + <property name="groupContextKey" column="groupcontext_fk" type="long" not-null="false"/> <many-to-one name="resource" diff --git a/src/main/java/org/olat/group/area/BGAreaManager.java b/src/main/java/org/olat/group/area/BGAreaManager.java index aa4cce5354f086540c13a6a9d5d71813eec4fc45..99bd66830f40bdf2f43017cc552538a46db79787 100644 --- a/src/main/java/org/olat/group/area/BGAreaManager.java +++ b/src/main/java/org/olat/group/area/BGAreaManager.java @@ -25,7 +25,9 @@ package org.olat.group.area; +import java.io.File; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Set; @@ -190,4 +192,7 @@ public interface BGAreaManager { * @return */ public abstract boolean checkIfOneOrMoreNameExistsInContext(Set<String> allNames, OLATResource resource); + + + public File archiveAreaMembers(OLATResource resource, List<String> columnList, List<BGArea> areaList, String archiveType, Locale locale, String charset); } \ No newline at end of file diff --git a/src/main/java/org/olat/group/area/BGAreaManagerImpl.java b/src/main/java/org/olat/group/area/BGAreaManagerImpl.java index d24083df760cce2a97131ae35ff27719838f849c..228335e85788e5863477091f27197a2ef330f572 100644 --- a/src/main/java/org/olat/group/area/BGAreaManagerImpl.java +++ b/src/main/java/org/olat/group/area/BGAreaManagerImpl.java @@ -25,11 +25,13 @@ package org.olat.group.area; +import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Set; @@ -45,8 +47,10 @@ import org.olat.core.util.coordinate.SyncerCallback; import org.olat.core.util.coordinate.SyncerExecutor; import org.olat.group.BusinessGroup; import org.olat.group.BusinessGroupImpl; +import org.olat.group.manager.BusinessGroupArchiver; import org.olat.resource.OLATResource; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; /** * Description:<BR/> Implementation of the business group area manager <P/> @@ -54,10 +58,13 @@ import org.springframework.beans.factory.annotation.Autowired; * * @author gnaegi */ +@Service("areaManager") public class BGAreaManagerImpl extends BasicManager implements BGAreaManager { @Autowired private DB dbInstance; + @Autowired + private BusinessGroupArchiver businessGroupArchiver; /** @@ -386,4 +393,9 @@ public class BGAreaManagerImpl extends BasicManager implements BGAreaManager { .setParameter("areaKey", area.getKey()) .executeUpdate(); } + + @Override + public File archiveAreaMembers(OLATResource resource, List<String> columnList, List<BGArea> areaList, String archiveType, Locale locale, String charset) { + return businessGroupArchiver.archiveAreaMembers(resource, columnList, areaList, archiveType, locale, charset); + } } \ No newline at end of file diff --git a/src/main/java/org/olat/group/delete/ReadyToDeleteController.java b/src/main/java/org/olat/group/delete/ReadyToDeleteController.java index 4ebf6ea94754746add2e5cee8ce37f566f5b3bd2..f9e130f09d16d009e03ebc657b0ef218e63458d9 100644 --- a/src/main/java/org/olat/group/delete/ReadyToDeleteController.java +++ b/src/main/java/org/olat/group/delete/ReadyToDeleteController.java @@ -49,8 +49,8 @@ import org.olat.core.gui.control.generic.modal.DialogBoxUIFactory; import org.olat.core.gui.translator.PackageTranslator; import org.olat.core.util.Util; import org.olat.group.BusinessGroup; +import org.olat.group.BusinessGroupModule; import org.olat.group.BusinessGroupService; -import org.olat.group.manager.BusinessGroupDeletionManager; import org.olat.group.ui.BGTranslatorFactory; import org.olat.group.ui.main.BGMainController; @@ -75,7 +75,7 @@ public class ReadyToDeleteController extends BasicController { private DialogBoxController deleteConfirmController; private PackageTranslator tableModelTypeTranslator; - private final BusinessGroupDeletionManager bgDeletionManager; + private final BusinessGroupModule businessGroupModule; private final BusinessGroupService businessGroupService; /** @@ -85,7 +85,7 @@ public class ReadyToDeleteController extends BasicController { */ public ReadyToDeleteController(UserRequest ureq, WindowControl wControl) { super(ureq, wControl); - bgDeletionManager = CoreSpringFactory.getImpl(BusinessGroupDeletionManager.class); + businessGroupModule = CoreSpringFactory.getImpl(BusinessGroupModule.class); businessGroupService = CoreSpringFactory.getImpl(BusinessGroupService.class); /* @@ -143,7 +143,7 @@ public class ReadyToDeleteController extends BasicController { } } else if (source == deleteConfirmController) { if (DialogBoxUIFactory.isOkEvent(event)) { - bgDeletionManager.deleteGroups(groupsReadyToDelete); + businessGroupService.deleteGroupsAfterLifeCycle(groupsReadyToDelete); showInfo("readyToDelete.deleted.msg"); } updateGroupList(); @@ -184,13 +184,13 @@ public class ReadyToDeleteController extends BasicController { VelocityContainer readyToDeleteContent = createVelocityContainer("readyToDelete"); readyToDeleteContent.put("readyToDelete", tableCtr.getInitialComponent()); readyToDeleteContent.contextPut("header", translate("ready.to.delete.header", - Integer.toString(bgDeletionManager.getDeleteEmailDuration()) )); + Integer.toString(businessGroupModule.getDeleteEmailDuration()) )); readyToDeletePanel.setContent(readyToDeleteContent); } protected void updateGroupList() { - List<BusinessGroup> l = bgDeletionManager.getGroupsReadyToDelete(bgDeletionManager.getDeleteEmailDuration()); + List<BusinessGroup> l = businessGroupService.getGroupsReadyToDelete(businessGroupModule.getDeleteEmailDuration()); redtm = new GroupDeleteTableModel(l,tableModelTypeTranslator); tableCtr.setTableDataModel(redtm); } diff --git a/src/main/java/org/olat/group/delete/SelectionController.java b/src/main/java/org/olat/group/delete/SelectionController.java index 872f1deb6597fc2ed27ba06d9411c31c59565204..18c8113f55db69d4667661d97240f9339d8e7714 100644 --- a/src/main/java/org/olat/group/delete/SelectionController.java +++ b/src/main/java/org/olat/group/delete/SelectionController.java @@ -59,8 +59,8 @@ import org.olat.core.util.Util; import org.olat.core.util.mail.MailNotificationEditController; import org.olat.core.util.mail.MailTemplate; import org.olat.group.BusinessGroup; +import org.olat.group.BusinessGroupModule; import org.olat.group.BusinessGroupService; -import org.olat.group.manager.BusinessGroupDeletionManager; import org.olat.group.ui.BGTranslatorFactory; import org.olat.group.ui.main.BGMainController; @@ -91,7 +91,7 @@ public class SelectionController extends BasicController { private CloseableModalController cmc; - private final BusinessGroupDeletionManager bgDeletionManager; + private final BusinessGroupModule businessGroupModule; private final BusinessGroupService businessGroupService; /** @@ -102,7 +102,7 @@ public class SelectionController extends BasicController { public SelectionController(UserRequest ureq, WindowControl wControl) { super(ureq, wControl); - bgDeletionManager = CoreSpringFactory.getImpl(BusinessGroupDeletionManager.class); + businessGroupModule = CoreSpringFactory.getImpl(BusinessGroupModule.class); businessGroupService = CoreSpringFactory.getImpl(BusinessGroupService.class); PackageTranslator fallbackTrans = new PackageTranslator(PACKAGE_BG_MAIN_CONTROLLER, ureq.getLocale()); @@ -126,7 +126,7 @@ public class SelectionController extends BasicController { selectionListContent = createVelocityContainer("selectionlist"); selectionListContent.put("repositorylist", tableCtr.getInitialComponent() ); selectionListContent.contextPut("header", translate("selection.delete.header", - new String[] { Integer.toString(bgDeletionManager.getLastUsageDuration()) })); + new String[] { Integer.toString(businessGroupModule.getLastUsageDuration()) })); editParameterLink = LinkFactory.createButtonXSmall("button.editParameter", selectionListContent, this); deleteSelectionPanel.setContent(selectionListContent); } @@ -140,7 +140,7 @@ public class SelectionController extends BasicController { if (source == editParameterLink) { removeAsListenerAndDispose(selectionForm); - selectionForm = new SelectionForm(ureq, getWindowControl(), bgDeletionManager); + selectionForm = new SelectionForm(ureq, getWindowControl(), businessGroupModule); listenTo(selectionForm); removeAsListenerAndDispose(cmc); @@ -162,8 +162,8 @@ public class SelectionController extends BasicController { public void event(UserRequest ureq, Controller source, Event event) { if (source == selectionForm) { if (event == Event.DONE_EVENT) { - bgDeletionManager.setLastUsageDuration(selectionForm.getLastUsageDuration()); - bgDeletionManager.setDeleteEmailDuration(selectionForm.getDeleteEmailDuration()); + businessGroupModule.setLastUsageDuration(selectionForm.getLastUsageDuration()); + businessGroupModule.setDeleteEmailDuration(selectionForm.getDeleteEmailDuration()); initializeContent(); } else if (event == Event.CANCELLED_EVENT) { fireEvent(ureq, Event.CANCELLED_EVENT); @@ -187,7 +187,7 @@ public class SelectionController extends BasicController { initializeContent(); } else if (source == deleteGroupMailCtr) { if (event == Event.DONE_EVENT) { - String warningMessage = bgDeletionManager.sendDeleteEmailTo( + String warningMessage = businessGroupService.sendDeleteEmailTo( selectedGroups, deleteGroupMailCtr.getMailTemplate(), deleteGroupMailCtr.isTemplateChanged(), KEY_EMAIL_SUBJECT, KEY_EMAIL_BODY, ureq.getIdentity(), (PackageTranslator) getTranslator() @@ -261,7 +261,7 @@ public class SelectionController extends BasicController { } public void updateGroupList() { - List<BusinessGroup> l = bgDeletionManager.getDeletableGroups(bgDeletionManager.getLastUsageDuration()); + List<BusinessGroup> l = businessGroupService.getDeletableGroups(businessGroupModule.getLastUsageDuration()); redtm = new GroupDeleteTableModel(l, tableModelTypeTranslator); tableCtr.setTableDataModel(redtm); } @@ -290,7 +290,7 @@ class SelectionForm extends FormBasicController { private IntegerElement lastUsageDuration; private IntegerElement emailDuration; - private final BusinessGroupDeletionManager bgDeletionManager; + private final BusinessGroupModule businessGroupModule; /** * @param name @@ -299,9 +299,9 @@ class SelectionForm extends FormBasicController { * validation takes place */ - public SelectionForm(UserRequest ureq, WindowControl wControl, BusinessGroupDeletionManager bgDeletionManager) { + public SelectionForm(UserRequest ureq, WindowControl wControl, BusinessGroupModule businessGroupModule) { super(ureq, wControl); - this.bgDeletionManager = bgDeletionManager; + this.businessGroupModule = businessGroupModule; initForm(ureq); } @@ -325,8 +325,8 @@ class SelectionForm extends FormBasicController { @Override protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) { - lastUsageDuration= uifactory.addIntegerElement("lastUsageDuration", "edit.parameter.form.lastusage.duration", bgDeletionManager.getLastUsageDuration(), formLayout); - emailDuration = uifactory.addIntegerElement("emailDuration", "edit.parameter.form.email.duration", bgDeletionManager.getDeleteEmailDuration(), formLayout); + lastUsageDuration= uifactory.addIntegerElement("lastUsageDuration", "edit.parameter.form.lastusage.duration", businessGroupModule.getLastUsageDuration(), formLayout); + emailDuration = uifactory.addIntegerElement("emailDuration", "edit.parameter.form.email.duration", businessGroupModule.getDeleteEmailDuration(), formLayout); lastUsageDuration.setMinValueCheck(1, null); emailDuration.setMinValueCheck(1, null); diff --git a/src/main/java/org/olat/group/delete/StatusController.java b/src/main/java/org/olat/group/delete/StatusController.java index 01936815029de4ffa502881aa34a89bc789c6f2e..7f3c3ea89dbb9c1e98b6c509c4ac2192ded82398 100644 --- a/src/main/java/org/olat/group/delete/StatusController.java +++ b/src/main/java/org/olat/group/delete/StatusController.java @@ -45,8 +45,8 @@ import org.olat.core.gui.control.controller.BasicController; import org.olat.core.gui.translator.PackageTranslator; import org.olat.core.util.Util; import org.olat.group.BusinessGroup; +import org.olat.group.BusinessGroupModule; import org.olat.group.BusinessGroupService; -import org.olat.group.manager.BusinessGroupDeletionManager; import org.olat.group.ui.BGTranslatorFactory; import org.olat.group.ui.main.BGMainController; @@ -68,7 +68,7 @@ public class StatusController extends BasicController { private GroupDeleteTableModel redtm; private PackageTranslator tableModelTypeTranslator; - private final BusinessGroupDeletionManager bgDeletionManager; + private final BusinessGroupModule businessGroupModule; private final BusinessGroupService businessGroupService; @@ -80,7 +80,7 @@ public class StatusController extends BasicController { public StatusController(UserRequest ureq, WindowControl wControl) { super(ureq, wControl); - bgDeletionManager = CoreSpringFactory.getImpl(BusinessGroupDeletionManager.class); + businessGroupModule = CoreSpringFactory.getImpl(BusinessGroupModule.class); businessGroupService = CoreSpringFactory.getImpl(BusinessGroupService.class); PackageTranslator fallbackTrans = new PackageTranslator(PACKAGE_BG_MAIN_CONTROLLER, ureq.getLocale()); @@ -94,7 +94,7 @@ public class StatusController extends BasicController { repositoryDeleteStatusPanel.addListener(this); myContent.put("repositoryDeleteStatusPanel", repositoryDeleteStatusPanel); myContent.contextPut("header", translate("status.delete.email.header", - new String [] { Integer.toString(bgDeletionManager.getDeleteEmailDuration()) })); + new String [] { Integer.toString(businessGroupModule.getDeleteEmailDuration()) })); initializeTableController(ureq); putInitialPanel(myContent); @@ -148,7 +148,7 @@ public class StatusController extends BasicController { } protected void updateGroupList() { - List<BusinessGroup> l = bgDeletionManager.getGroupsInDeletionProcess(bgDeletionManager.getDeleteEmailDuration()); + List<BusinessGroup> l = businessGroupService.getGroupsInDeletionProcess(businessGroupModule.getDeleteEmailDuration()); redtm = new GroupDeleteTableModel(l, tableModelTypeTranslator); tableCtr.setTableDataModel(redtm); } diff --git a/src/main/java/org/olat/group/manager/BusinessGroupAddManager.java b/src/main/java/org/olat/group/manager/BusinessGroupAddManager.java deleted file mode 100644 index 61d83a01fd32f0b79f68ec90f0c228abf11193d7..0000000000000000000000000000000000000000 --- a/src/main/java/org/olat/group/manager/BusinessGroupAddManager.java +++ /dev/null @@ -1,144 +0,0 @@ -/** - * <a href="http://www.openolat.org"> - * OpenOLAT - Online Learning and Training</a><br> - * <p> - * Licensed under the Apache License, Version 2.0 (the "License"); <br> - * you may not use this file except in compliance with the License.<br> - * You may obtain a copy of the License at the - * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> - * <p> - * Unless required by applicable law or agreed to in writing,<br> - * software distributed under the License is distributed on an "AS IS" BASIS, <br> - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> - * See the License for the specific language governing permissions and <br> - * limitations under the License. - * <p> - * Initial code contributed and copyrighted by<br> - * frentix GmbH, http://www.frentix.com - * <p> - */ -package org.olat.group.manager; - -import java.util.ArrayList; -import java.util.List; - -import org.olat.admin.user.groups.AddToGroupsEvent; -import org.olat.basesecurity.BaseSecurity; -import org.olat.core.id.Identity; -import org.olat.core.manager.BasicManager; -import org.olat.core.util.coordinate.CoordinatorManager; -import org.olat.core.util.coordinate.SyncerExecutor; -import org.olat.core.util.mail.MailTemplate; -import org.olat.core.util.mail.MailerResult; -import org.olat.core.util.mail.MailerWithTemplate; -import org.olat.group.BusinessGroup; -import org.olat.group.BusinessGroupService; -import org.olat.group.ui.BGConfigFlags; -import org.olat.group.ui.BGMailHelper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -/** - * Description:<br> - * Functions to add an identity to multiple groups at once. - * - * <P> - * Initial Date: 09.05.2011 <br> - * @author Roman Haag, frentix GmbH, roman.haag@frentix.com - */ -@Service("groupAddManager") -public class BusinessGroupAddManager extends BasicManager { - - @Autowired - private BaseSecurity securityManager; - @Autowired - private BusinessGroupService businessGroupService; - - - /** - * add identity to given groups as owner and/or participant - * @param ownGroups - * @param partGroups - * @param mailGroups - * @param ident - * @param addingIdentity - * @return - */ - public String[] addIdentityToGroups(List<Long> ownGroups, List<Long> partGroups, List<Long> mailGroups, final Identity ident, final Identity addingIdentity) { - AddToGroupsEvent groupsEv = new AddToGroupsEvent(ownGroups, partGroups, mailGroups); - return addIdentityToGroups(groupsEv, ident, addingIdentity); - } - - /** - * add identity to given groups as owner and/or participant - * @param groupsEv - * @param ident the identity to be added - * @param addingIdentity the identity who does this action - * @return - */ - public String[] addIdentityToGroups(AddToGroupsEvent groupsEv, final Identity ident, final Identity addingIdentity) { - final BGConfigFlags flags = BGConfigFlags.createBuddyGroupDefaultFlags(); - String[] resultTextArgs = new String[2]; - boolean addToAnyGroup = false; - - // notify user about add for following groups: - List<Long> notifyAboutAdd = new ArrayList<Long>(); - List<Long> mailKeys = groupsEv.getMailForGroupsList(); - - // add to owner groups - List<Long> ownerKeys = groupsEv.getOwnerGroupKeys(); - String ownerGroupnames = ""; - - List<BusinessGroup> groups = businessGroupService.loadBusinessGroups(ownerKeys); - for (BusinessGroup group : groups) { - if (group != null && !securityManager.isIdentityInSecurityGroup(ident, group.getOwnerGroup())){ -// seems not to work, but would be the way to go! -// ThreadLocalUserActivityLogger.addLoggingResourceInfo(LoggingResourceable.wrap(group)); - businessGroupService.addOwner(addingIdentity, ident, group, flags); - ownerGroupnames += group.getName() + ", "; - addToAnyGroup = true; - if (!notifyAboutAdd.contains(group.getKey()) && mailKeys.contains(group.getKey())) notifyAboutAdd.add(group.getKey()); - } - } - resultTextArgs[0] = ownerGroupnames.substring(0, ownerGroupnames.length() > 0 ? ownerGroupnames.length() - 2 : 0); - - // add to participant groups - List<Long> participantKeys = groupsEv.getParticipantGroupKeys(); - String participantGroupnames = ""; - List<BusinessGroup> participantGroups = businessGroupService.loadBusinessGroups(participantKeys); - for (BusinessGroup group : participantGroups) { - if (group != null && !securityManager.isIdentityInSecurityGroup(ident, group.getPartipiciantGroup())) { - final BusinessGroup toAddGroup = group; -// seems not to work, but would be the way to go! -// ThreadLocalUserActivityLogger.addLoggingResourceInfo(LoggingResourceable.wrap(group)); - CoordinatorManager.getInstance().getCoordinator().getSyncer().doInSync(group, new SyncerExecutor(){ - public void execute() { - businessGroupService.addParticipant(addingIdentity, ident, toAddGroup, flags); - }}); - participantGroupnames += group.getName() + ", "; - addToAnyGroup = true; - if (!notifyAboutAdd.contains(group.getKey()) && mailKeys.contains(group.getKey())) notifyAboutAdd.add(group.getKey()); - } - } - resultTextArgs[1] = participantGroupnames.substring(0, participantGroupnames.length() > 0 ? participantGroupnames.length() - 2 : 0); - - // send notification mails - - List<BusinessGroup> notifGroups = businessGroupService.loadBusinessGroups(notifyAboutAdd); - for (BusinessGroup group : notifGroups) { - MailTemplate mailTemplate = BGMailHelper.createAddParticipantMailTemplate(group, addingIdentity); - MailerWithTemplate mailer = MailerWithTemplate.getInstance(); - MailerResult mailerResult = mailer.sendMail(null, ident, null, null, mailTemplate, null); - if (mailerResult.getReturnCode() != MailerResult.OK){ - logDebug("Problems sending Group invitation mail for identity: " + ident.getName() + " and group: " - + group.getName() + " key: " + group.getKey() + " mailerresult: " + mailerResult.getReturnCode(), null); - } - } - - if (addToAnyGroup) { - return resultTextArgs; - } else { - return null; - } - } -} diff --git a/src/main/java/org/olat/group/manager/BusinessGroupArchiver.java b/src/main/java/org/olat/group/manager/BusinessGroupArchiver.java index 455602f990594069138c2dab4f39778efc7e362f..229c9318c9cddd524e6f52dbd76c819823f19231 100644 --- a/src/main/java/org/olat/group/manager/BusinessGroupArchiver.java +++ b/src/main/java/org/olat/group/manager/BusinessGroupArchiver.java @@ -214,17 +214,17 @@ public class BusinessGroupArchiver { buf.append( translator.translate("table.subject.addeddate") ); buf.append(EOL); } - - public void archiveBGContext(OLATResource resource, File archiveFile) { - FileUtils.save(archiveFile, toXls(resource), "utf-8"); + + public void archiveGroups(List<BusinessGroup> groups, File archiveFile) { + FileUtils.save(archiveFile, toXls(groups), "utf-8"); } - private String toXls(OLATResource resource) { + private String toXls(List<BusinessGroup> groups) { StringBuffer buf = new StringBuffer(); // Export Context Header buf.append(translator.translate("archive.group.context.name")); buf.append(DELIMITER); - buf.append(resource.getResourceableTypeName()); + buf.append(""); buf.append(DELIMITER); buf.append(translator.translate("archive.group.context.type")); buf.append(DELIMITER); @@ -235,7 +235,6 @@ public class BusinessGroupArchiver { buf.append(FilterFactory.getHtmlTagsFilter().filter("Description")); buf.append(EOL); - List<BusinessGroup> groups = businessGroupService.findBusinessGroups(null, null, false, false, resource, 0, -1); for (BusinessGroup group : groups) { buf.append( toXls(group) ); buf.append(EOL); diff --git a/src/main/java/org/olat/group/manager/BusinessGroupDAO.java b/src/main/java/org/olat/group/manager/BusinessGroupDAO.java index 59c7493b95be7f5375fdb8b4919a7c2a877efc6a..00c6777bf2e4e742fba39e6cb408a7c6f4ab65be 100644 --- a/src/main/java/org/olat/group/manager/BusinessGroupDAO.java +++ b/src/main/java/org/olat/group/manager/BusinessGroupDAO.java @@ -19,6 +19,7 @@ */ package org.olat.group.manager; +import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -26,6 +27,7 @@ import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.LockModeType; +import javax.persistence.TemporalType; import javax.persistence.TypedQuery; import org.olat.basesecurity.BaseSecurity; @@ -34,6 +36,7 @@ import org.olat.basesecurity.IdentityImpl; import org.olat.basesecurity.SecurityGroup; import org.olat.basesecurity.SecurityGroupMembershipImpl; import org.olat.collaboration.CollaborationTools; +import org.olat.commons.lifecycle.LifeCycleEntry; import org.olat.core.commons.persistence.DB; import org.olat.core.id.Identity; import org.olat.core.logging.OLog; @@ -41,6 +44,7 @@ import org.olat.core.logging.Tracing; import org.olat.core.util.StringHelper; import org.olat.group.BusinessGroup; import org.olat.group.BusinessGroupImpl; +import org.olat.group.BusinessGroupService; import org.olat.group.model.BGResourceRelation; import org.olat.group.model.SearchBusinessGroupParams; import org.olat.group.properties.BusinessGroupPropertyManager; @@ -79,8 +83,13 @@ public class BusinessGroupDAO { String realType = type == null ? BusinessGroup.TYPE_LEARNINGROUP : type; businessgroup = new BusinessGroupImpl(realType, name, description, ownerGroup, participantGroup, waitingGroup); - businessgroup.setMinParticipants(minParticipants); - businessgroup.setMaxParticipants(maxParticipants); + if(minParticipants >= 0) { + businessgroup.setMinParticipants(minParticipants); + } + if(maxParticipants > 0) { + businessgroup.setMaxParticipants(maxParticipants); + } + businessgroup.setWaitingListEnabled(waitingListEnabled); businessgroup.setAutoCloseRanksEnabled(autoCloseRanksEnabled); @@ -136,9 +145,12 @@ public class BusinessGroupDAO { if(ids == null || ids.isEmpty()) { return Collections.emptyList(); } - - EntityManager em = dbInstance.getCurrentEntityManager(); - List<BusinessGroup> groups = em.createQuery("select grp from " + BusinessGroupImpl.class.getName() + " grp where grp.id in (:ids)", BusinessGroup.class) + StringBuilder sb = new StringBuilder(); + sb.append("select grp from ").append(BusinessGroupImpl.class.getName()).append(" grp where grp.id in (:ids)"); + + List<BusinessGroup> groups = dbInstance.getCurrentEntityManager() + .createQuery(sb.toString(), BusinessGroup.class) + .setParameter("ids", ids) .getResultList(); return groups; } @@ -167,6 +179,71 @@ public class BusinessGroupDAO { em.remove(group); } + public List<BusinessGroup> getDeletableGroups(int lastLoginDuration) { + Calendar lastUsageLimit = Calendar.getInstance(); + lastUsageLimit.add(Calendar.MONTH, - lastLoginDuration); + log.debug("lastLoginLimit=" + lastUsageLimit); + // 1. get all business-groups with last usage > x + StringBuilder sb = new StringBuilder(); + sb.append("select gr from ").append(BusinessGroupImpl.class).append(" as gr ") + .append(" where (gr.lastUsage = null or gr.lastUsage < :lastUsage)"); + List<BusinessGroup> groups = dbInstance.getCurrentEntityManager() + .createQuery(sb.toString(), BusinessGroup.class) + .setParameter("lastUsage", lastUsageLimit.getTime(), TemporalType.TIMESTAMP) + .getResultList(); + + // 2. get all businness-groups in deletion-process (email send) + StringBuilder sc = new StringBuilder(); + sc.append( "select gr from ").append(BusinessGroupImpl.class.getName()).append(" as gr") + .append(", ").append(LifeCycleEntry.class.getName()).append(" as le ") + .append(" where gr.key = le.persistentRef ") + .append(" and le.persistentTypeName ='org.olat.group.BusinessGroupImpl'" ) + .append(" and le.action ='" + BusinessGroupService.SEND_DELETE_EMAIL_ACTION + "'"); + List<BusinessGroup> groupsInProcess = dbInstance.getCurrentEntityManager() + .createQuery(sc.toString(), BusinessGroup.class) + .getResultList(); + + // 3. Remove all groups in deletion-process from all unused-groups + groups.removeAll(groupsInProcess); + return groups; + } + + public List<BusinessGroup> getGroupsInDeletionProcess(int deleteEmailDuration) { + Calendar deleteEmailLimit = Calendar.getInstance(); + deleteEmailLimit.add(Calendar.DAY_OF_MONTH, - (deleteEmailDuration - 1)); + log.debug("deleteEmailLimit=" + deleteEmailLimit); + + StringBuilder sb = new StringBuilder(); + sb.append("select gr from ").append(BusinessGroupImpl.class.getName()).append(" as gr") + .append(" , ").append(LifeCycleEntry.class.getName()).append(" as le") + .append(" where gr.key = le.persistentRef ") + .append(" and le.persistentTypeName ='org.olat.group.BusinessGroupImpl'") + .append(" and le.action ='" + BusinessGroupService.SEND_DELETE_EMAIL_ACTION + "' and le.lcTimestamp >= :deleteEmailDate "); + + List<BusinessGroup> groups = dbInstance.getCurrentEntityManager().createQuery(sb.toString(), BusinessGroup.class) + .setParameter("deleteEmailDate", deleteEmailLimit.getTime(), TemporalType.TIMESTAMP) + .getResultList(); + return groups; + } + + public List<BusinessGroup> getGroupsReadyToDelete(int deleteEmailDuration) { + Calendar deleteEmailLimit = Calendar.getInstance(); + deleteEmailLimit.add(Calendar.DAY_OF_MONTH, - (deleteEmailDuration - 1)); + log.debug("deleteEmailLimit=" + deleteEmailLimit); + + StringBuilder sb = new StringBuilder(); + sb.append("select gr from ").append(BusinessGroupImpl.class.getName()).append(" as gr") + .append(" , ").append(LifeCycleEntry.class.getName()).append(" as le") + .append(" where gr.key = le.persistentRef ") + .append(" and le.persistentTypeName ='org.olat.group.BusinessGroupImpl'") + .append(" and le.action ='" + BusinessGroupService.SEND_DELETE_EMAIL_ACTION + "' and le.lcTimestamp < :deleteEmailDate "); + + List<BusinessGroup> groups = dbInstance.getCurrentEntityManager().createQuery(sb.toString(), BusinessGroup.class) + .setParameter("deleteEmailDate", deleteEmailLimit.getTime(), TemporalType.TIMESTAMP) + .getResultList(); + return groups; + } + /** * Work with the hibernate session * @param group @@ -177,10 +254,10 @@ public class BusinessGroupDAO { return group; } - public boolean isIdentityInBusinessGroup(Identity identity, String name, String groupType, OLATResource resource) { + public boolean isIdentityInBusinessGroup(Identity identity, String name, OLATResource resource) { StringBuilder sb = new StringBuilder(); sb.append("select count(bgi) from ").append(BusinessGroupImpl.class.getName()).append(" bgi where") - .append(" bgi.name = :name") + .append(" bgi.name=:name") .append(" and (") .append(" bgi.partipiciantGroup in (") .append(" select participantMemberShip.securityGroup from ").append(SecurityGroupMembershipImpl.class.getName()).append(" participantMemberShip ") @@ -194,15 +271,12 @@ public class BusinessGroupDAO { .append(" )") .append(" and bgi in (") .append(" select relation.group from ").append(BGResourceRelation.class.getName()).append(" relation where relation.resource.key=:resourceKey") - .append(" )") - .append(" and bgi.type=:type"); + .append(" )"); - System.out.println(sb.toString()); Number count = dbInstance.getCurrentEntityManager().createQuery(sb.toString(), Number.class) .setParameter("identityKey", identity.getKey()) .setParameter("name", name) .setParameter("resourceKey", resource.getKey()) - .setParameter("type", groupType) .getSingleResult(); return count.intValue() > 0; } @@ -346,6 +420,10 @@ public class BusinessGroupDAO { query.append("left join fetch bgi.ownerGroup ownerGroup "); query.append("left join fetch bgi.partipiciantGroup participantGroup "); query.append("left join fetch bgi.waitingGroup waitingGroup "); + } else { + query.append("left join bgi.ownerGroup ownerGroup "); + query.append("left join bgi.partipiciantGroup participantGroup "); + query.append("left join bgi.waitingGroup waitingGroup "); } boolean where = false; @@ -406,6 +484,10 @@ public class BusinessGroupDAO { searchLikeAttribute(query, "bgi", "description", "search"); query.append(")"); } else { + if(StringHelper.containsNonWhitespace(params.getExactName())) { + where = where(query, where); + query.append("bgi.name=:exactName"); + } if(StringHelper.containsNonWhitespace(params.getName())) { where = where(query, where); searchLikeAttribute(query, "bgi", "name", "name"); @@ -451,6 +533,9 @@ public class BusinessGroupDAO { if(StringHelper.containsNonWhitespace(params.getNameOrDesc())) { dbq.setParameter("search", params.getNameOrDesc()); } else { + if(StringHelper.containsNonWhitespace(params.getExactName())) { + dbq.setParameter("exactName", params.getExactName()); + } if(StringHelper.containsNonWhitespace(params.getName())) { dbq.setParameter("name", params.getName()); } diff --git a/src/main/java/org/olat/group/manager/BusinessGroupDeletionManager.java b/src/main/java/org/olat/group/manager/BusinessGroupDeletionManager.java index 2d64aa0972d908a13de9dd0578bddcecbedd911b..1c0fca7975f1c9f899a809844fe730ad5776107d 100644 --- a/src/main/java/org/olat/group/manager/BusinessGroupDeletionManager.java +++ b/src/main/java/org/olat/group/manager/BusinessGroupDeletionManager.java @@ -27,7 +27,6 @@ package org.olat.group.manager; import java.io.File; import java.util.ArrayList; -import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -35,11 +34,8 @@ import java.util.Map; import org.olat.basesecurity.BaseSecurityManager; import org.olat.basesecurity.SecurityGroup; -import org.olat.collaboration.CollaborationToolsFactory; import org.olat.commons.lifecycle.LifeCycleManager; import org.olat.core.CoreSpringFactory; -import org.olat.core.commons.persistence.DBFactory; -import org.olat.core.commons.persistence.DBQuery; import org.olat.core.gui.translator.Translator; import org.olat.core.id.Identity; import org.olat.core.id.UserConstants; @@ -52,8 +48,6 @@ import org.olat.core.util.mail.MailerResult; import org.olat.core.util.mail.MailerWithTemplate; import org.olat.group.BusinessGroup; import org.olat.group.BusinessGroupService; -import org.olat.properties.Property; -import org.olat.properties.PropertyManager; import org.olat.repository.delete.service.DeletionModule; @@ -64,13 +58,6 @@ import org.olat.repository.delete.service.DeletionModule; public class BusinessGroupDeletionManager extends BasicManager { private static final String GROUP_ARCHIVE_DIR = "archive_deleted_groups"; - - private static final String PROPERTY_CATEGORY = "GroupDeletion"; - private static final String LAST_USAGE_DURATION_PROPERTY_NAME = "LastUsageDuration"; - private static final int DEFAULT_LAST_USAGE_DURATION = 24; - private static final String DELETE_EMAIL_DURATION_PROPERTY_NAME = "DeleteEmailDuration"; - private static final int DEFAULT_DELETE_EMAIL_DURATION = 30; - private static final String GROUPEXPORT_XML = "groupexport.xml"; private static final String GROUPARCHIVE_XLS = "grouparchive.xls"; @@ -93,21 +80,7 @@ public class BusinessGroupDeletionManager extends BasicManager { this.businessGroupService = businessGroupService; } - public void setLastUsageDuration(int lastUsageDuration) { - setProperty(LAST_USAGE_DURATION_PROPERTY_NAME, lastUsageDuration); - } - - public void setDeleteEmailDuration(int deleteEmailDuration) { - setProperty(DELETE_EMAIL_DURATION_PROPERTY_NAME, deleteEmailDuration); - } - - public int getLastUsageDuration() { - return getPropertyByName(LAST_USAGE_DURATION_PROPERTY_NAME, DEFAULT_LAST_USAGE_DURATION); - } - public int getDeleteEmailDuration() { - return getPropertyByName(DELETE_EMAIL_DURATION_PROPERTY_NAME, DEFAULT_DELETE_EMAIL_DURATION); - } public String sendDeleteEmailTo(List<BusinessGroup> selectedGroups, MailTemplate mailTemplate, boolean isTemplateChanged, String keyEmailSubject, String keyEmailBody, Identity sender, Translator pT) { @@ -182,75 +155,14 @@ public class BusinessGroupDeletionManager extends BasicManager { BusinessGroupService bgs = CoreSpringFactory.getImpl(BusinessGroupService.class); group = bgs.loadBusinessGroup(group); LifeCycleManager.createInstanceFor(group).markTimestampFor(BusinessGroupService.SEND_DELETE_EMAIL_ACTION); - group = bgs.mergeBusinessGroup(group); - } - - public List<BusinessGroup> getDeletableGroups(int lastLoginDuration) { - Calendar lastUsageLimit = Calendar.getInstance(); - lastUsageLimit.add(Calendar.MONTH, - lastLoginDuration); - logDebug("lastLoginLimit=" + lastUsageLimit); - // 1. get all businness-groups with lastusage > x - String query = "select gr from org.olat.group.BusinessGroupImpl as gr " - + " where (gr.lastUsage = null or gr.lastUsage < :lastUsage)" - + " and gr.type = :type "; - DBQuery dbq = DBFactory.getInstance().createQuery(query); - dbq.setDate("lastUsage", lastUsageLimit.getTime()); - dbq.setString("type", BusinessGroup.TYPE_BUDDYGROUP); - - - List groups = dbq.list(); - // 2. get all businness-groups in deletion-process (email send) - query = "select gr from org.olat.group.BusinessGroupImpl as gr" - + " , org.olat.commons.lifecycle.LifeCycleEntry as le" - + " where gr.key = le.persistentRef " - + " and le.persistentTypeName ='org.olat.group.BusinessGroupImpl'" - + " and le.action ='" + BusinessGroupService.SEND_DELETE_EMAIL_ACTION + "' "; - dbq = DBFactory.getInstance().createQuery(query); - List groupsInProcess = dbq.list(); - // 3. Remove all groups in deletion-process from all unused-groups - groups.removeAll(groupsInProcess); - return groups; - } - - //TODO gm ONLY BUDDY???? - public List<BusinessGroup> getGroupsInDeletionProcess(int deleteEmailDuration) { - Calendar deleteEmailLimit = Calendar.getInstance(); - deleteEmailLimit.add(Calendar.DAY_OF_MONTH, - (deleteEmailDuration - 1)); - logDebug("deleteEmailLimit=" + deleteEmailLimit); - String queryStr = "select gr from org.olat.group.BusinessGroupImpl as gr" - + " , org.olat.commons.lifecycle.LifeCycleEntry as le" - + " where gr.key = le.persistentRef " - + " and le.persistentTypeName ='org.olat.group.BusinessGroupImpl'" - + " and le.action ='" + BusinessGroupService.SEND_DELETE_EMAIL_ACTION + "' and le.lcTimestamp >= :deleteEmailDate " - + " and gr.type = :type "; - DBQuery dbq = DBFactory.getInstance().createQuery(queryStr); - dbq.setDate("deleteEmailDate", deleteEmailLimit.getTime()); - dbq.setString("type", BusinessGroup.TYPE_BUDDYGROUP); - return dbq.list(); + //group = bgs.updateBusinessGroup(group); } - //TODO gm ONLY BUDDY???? - public List<BusinessGroup> getGroupsReadyToDelete(int deleteEmailDuration) { - Calendar deleteEmailLimit = Calendar.getInstance(); - deleteEmailLimit.add(Calendar.DAY_OF_MONTH, - (deleteEmailDuration - 1)); - logDebug("deleteEmailLimit=" + deleteEmailLimit); - String queryStr = "select gr from org.olat.group.BusinessGroupImpl as gr" - + " , org.olat.commons.lifecycle.LifeCycleEntry as le" - + " where gr.key = le.persistentRef " - + " and le.persistentTypeName ='org.olat.group.BusinessGroupImpl'" - + " and le.action ='" + BusinessGroupService.SEND_DELETE_EMAIL_ACTION + "' and le.lcTimestamp < :deleteEmailDate " - + " and gr.type = :type "; - DBQuery dbq = DBFactory.getInstance().createQuery(queryStr); - dbq.setDate("deleteEmailDate", deleteEmailLimit.getTime()); - dbq.setString("type", BusinessGroup.TYPE_BUDDYGROUP); - return dbq.list(); - } - - public void deleteGroups(List<BusinessGroup> groups) { + protected void deleteGroups(List<BusinessGroup> groups) { for (BusinessGroup businessGroup : groups) { String archiveFileName = archive(getArchivFilePath(businessGroup), businessGroup); logAudit("Group-Deletion: archived businessGroup=" + businessGroup + " , archive-file-name=" + archiveFileName); - CollaborationToolsFactory.getInstance().getOrCreateCollaborationTools(businessGroup).deleteTools(businessGroup); + businessGroupService.deleteBusinessGroup(businessGroup); LifeCycleManager.createInstanceFor(businessGroup).deleteTimestampFor(BusinessGroupService.SEND_DELETE_EMAIL_ACTION); LifeCycleManager.createInstanceFor(businessGroup).markTimestampFor(GROUP_DELETED_ACTION, createLifeCycleLogDataFor(businessGroup)); @@ -299,29 +211,4 @@ public class BusinessGroupDeletionManager extends BasicManager { return module.getArchiveRootPath() + File.separator + GROUP_ARCHIVE_DIR + File.separator + DeletionModule.getArchiveDatePath() + File.separator + "del_group_" + businessGroup.getResourceableId(); } - - - ////////////////// - // Private Methods - ////////////////// - private int getPropertyByName(String name, int defaultValue) { - List<Property> properties = PropertyManager.getInstance().findProperties(null, null, null, PROPERTY_CATEGORY, name); - if (properties.size() == 0) { - return defaultValue; - } else { - return ((Property)properties.get(0)).getLongValue().intValue(); - } - } - - private void setProperty(String propertyName, int value) { - List<Property> properties = PropertyManager.getInstance().findProperties(null, null, null, PROPERTY_CATEGORY, propertyName); - Property property = null; - if (properties.size() == 0) { - property = PropertyManager.getInstance().createPropertyInstance(null, null, null, PROPERTY_CATEGORY, propertyName, null, new Long(value), null, null); - } else { - property = (Property)properties.get(0); - property.setLongValue( new Long(value) ); - } - PropertyManager.getInstance().saveProperty(property); - } } \ No newline at end of file diff --git a/src/main/java/org/olat/group/manager/BusinessGroupImportExport.java b/src/main/java/org/olat/group/manager/BusinessGroupImportExport.java index 3e83ed66bea7856d54e12a48a719ecead0fadb39..129b7c83d83d24ace13c5daf08404fd9c1286961 100644 --- a/src/main/java/org/olat/group/manager/BusinessGroupImportExport.java +++ b/src/main/java/org/olat/group/manager/BusinessGroupImportExport.java @@ -20,7 +20,11 @@ package org.olat.group.manager; import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Collections; import java.util.List; import org.olat.collaboration.CollaborationTools; @@ -29,6 +33,8 @@ import org.olat.core.logging.AssertException; import org.olat.core.logging.OLATRuntimeException; import org.olat.core.logging.OLog; import org.olat.core.logging.Tracing; +import org.olat.core.util.FileUtils; +import org.olat.core.util.StringHelper; import org.olat.group.BusinessGroup; import org.olat.group.BusinessGroupService; import org.olat.group.area.BGArea; @@ -56,7 +62,117 @@ public class BusinessGroupImportExport { private BusinessGroupService businessGroupService; + public void exportGroups(List<BusinessGroup> groups, File fExportFile) { + if (groups == null || groups.isEmpty()) + return; // nothing to do... says Florian. + OLATGroupExport root = new OLATGroupExport(); + // export areas + root.setAreas(new AreaCollection()); + root.getAreas().setGroups(new ArrayList<Area>()); + + // export groups + root.setGroups(new GroupCollection()); + root.getGroups().setGroups(new ArrayList<Group>()); + for (BusinessGroup group : groups) { + Group newGroup = exportGroup(fExportFile, group); + root.getGroups().getGroups().add(newGroup); + } + saveGroupConfiguration(fExportFile, root); + } + + public void exportGroup(BusinessGroup group, File fExportFile) { + OLATGroupExport root = new OLATGroupExport(); + Group newGroup = exportGroup(fExportFile, group); + root.setGroups(new GroupCollection()); + root.getGroups().setGroups(new ArrayList<Group>()); + root.getGroups().getGroups().add(newGroup); + saveGroupConfiguration(fExportFile, root); + } + + private Group exportGroup(File fExportFile, BusinessGroup group) { + Group newGroup = new Group(); + newGroup.name = group.getName(); + if (group.getMinParticipants() != null) { + newGroup.minParticipants = group.getMinParticipants(); + } + if (group.getMaxParticipants() != null) { + newGroup.maxParticipants = group.getMaxParticipants(); + } + if (group.getWaitingListEnabled() != null) { + newGroup.waitingList = group.getWaitingListEnabled(); + } + if (group.getAutoCloseRanksEnabled() != null) { + newGroup.autoCloseRanks = group.getAutoCloseRanksEnabled(); + } + if(StringHelper.containsNonWhitespace(group.getDescription())) { + newGroup.description = Collections.singletonList(group.getDescription()); + } + // collab tools + + CollabTools toolsConfig = new CollabTools(); + CollaborationTools ct = CollaborationToolsFactory.getInstance().getOrCreateCollaborationTools(group); + for (int i = 0; i < CollaborationTools.TOOLS.length; i++) { + try { + Field field = toolsConfig.getClass().getField(CollaborationTools.TOOLS[i]); + field.setBoolean(toolsConfig, ct.isToolEnabled(CollaborationTools.TOOLS[i])); + } catch (Exception e) { + log.error("", e); + } + } + newGroup.tools = toolsConfig; + + Long calendarAccess = ct.lookupCalendarAccess(); + if (calendarAccess != null) { + newGroup.calendarAccess = calendarAccess; + } + //fxdiff VCRP-8: collaboration tools folder access control + Long folderAccess = ct.lookupFolderAccess(); + if(folderAccess != null) { + newGroup.folderAccess = folderAccess; + } + String info = ct.lookupNews(); + if (info != null && !info.trim().equals("")) { + newGroup.info = info.trim(); + } + + log.debug("fExportFile.getParent()=" + fExportFile.getParent()); + ct.archive(fExportFile.getParent()); + // export membership + List<BGArea> bgAreas = areaManager.findBGAreasOfBusinessGroup(group); + newGroup.areaRelations = new ArrayList<String>(); + for (BGArea areaRelation : bgAreas) { + newGroup.areaRelations.add(areaRelation.getName()); + } + // export properties + BusinessGroupPropertyManager bgPropertyManager = new BusinessGroupPropertyManager(group); + boolean showOwners = bgPropertyManager.showOwners(); + boolean showParticipants = bgPropertyManager.showPartips(); + boolean showWaitingList = bgPropertyManager.showWaitingList(); + + newGroup.showOwners = showOwners; + newGroup.showParticipants = showParticipants; + newGroup.showWaitingList = showWaitingList; + return newGroup; + } + + private void saveGroupConfiguration(File fExportFile, OLATGroupExport root) { + FileOutputStream fOut = null; + try { + fOut = new FileOutputStream(fExportFile); + xstream.toXML(root, fOut); + } catch (IOException ioe) { + throw new OLATRuntimeException( + "Error writing group configuration during group export.", + ioe); + } catch (Exception cfe) { + throw new OLATRuntimeException( + "Error writing group configuration during group export.", + cfe); + } finally { + FileUtils.closeSafely(fOut); + } + } public void importGroups(OLATResource resource, File fGroupExportXML) { if (!fGroupExportXML.exists()) @@ -90,17 +206,17 @@ public class BusinessGroupImportExport { String groupDesc = (group.description != null && !group.description.isEmpty()) ? group.description.get(0) : ""; // get min/max participants - Integer groupMinParticipants = group.minParticipants; - Integer groupMaxParticipants = group.maxParticipants; + int groupMinParticipants = group.minParticipants == null ? -1 : group.minParticipants.intValue(); + int groupMaxParticipants = group.maxParticipants == null ? -1 : group.maxParticipants.intValue(); // waiting list configuration - Boolean waitingList = group.waitingList; - if (waitingList == null) { - waitingList = Boolean.FALSE; + boolean waitingList = false; + if (group.waitingList != null) { + waitingList = group.waitingList.booleanValue(); } - Boolean enableAutoCloseRanks = group.autoCloseRanks; - if (enableAutoCloseRanks == null) { - enableAutoCloseRanks = Boolean.FALSE; + boolean enableAutoCloseRanks = false; + if (group.autoCloseRanks != null) { + enableAutoCloseRanks = group.autoCloseRanks.booleanValue(); } String type = BusinessGroup.TYPE_LEARNINGROUP;//TODO gm diff --git a/src/main/java/org/olat/group/manager/BusinessGroupRelationDAO.java b/src/main/java/org/olat/group/manager/BusinessGroupRelationDAO.java index d51061ad859515623a01391fa535c98a7e5062ac..80966864cc07b5feea742c11f5dd1545b76e5ee3 100644 --- a/src/main/java/org/olat/group/manager/BusinessGroupRelationDAO.java +++ b/src/main/java/org/olat/group/manager/BusinessGroupRelationDAO.java @@ -24,6 +24,7 @@ import java.util.Collection; import java.util.Collections; import java.util.List; +import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import org.olat.core.commons.persistence.DB; @@ -44,6 +45,20 @@ public class BusinessGroupRelationDAO { @Autowired private DB dbInstance; + public void deleteRelations(BusinessGroup group) { + StringBuilder sb = new StringBuilder(); + sb.append("select rel from ").append(BGResourceRelation.class.getName()).append(" as rel ") + .append(" where rel.group.key=:groupKey"); + + EntityManager em = dbInstance.getCurrentEntityManager(); + List<BGResourceRelation> relations = em.createQuery(sb.toString(), BGResourceRelation.class) + .setParameter("groupKey", group.getKey()) + .getResultList(); + + for(BGResourceRelation relation:relations) { + em.remove(relation); + } + } public List<OLATResource> findResources(Collection<BusinessGroup> groups, int firstResult, int maxResults) { if(groups == null || groups.isEmpty()) { @@ -67,7 +82,6 @@ public class BusinessGroupRelationDAO { return query.getResultList(); } - public List<RepositoryEntry> findRepositoryEntries(Collection<BusinessGroup> groups, int firstResult, int maxResults) { if(groups == null || groups.isEmpty()) { return Collections.emptyList(); diff --git a/src/main/java/org/olat/group/manager/BusinessGroupServiceImpl.java b/src/main/java/org/olat/group/manager/BusinessGroupServiceImpl.java index 77c46186314a9b697a19ede74fdcfc7a13ae977f..9458dc86f85be00c45eb20b2bd6368a0128a73f0 100644 --- a/src/main/java/org/olat/group/manager/BusinessGroupServiceImpl.java +++ b/src/main/java/org/olat/group/manager/BusinessGroupServiceImpl.java @@ -33,7 +33,6 @@ import java.util.Set; import org.hibernate.ObjectNotFoundException; import org.hibernate.StaleObjectStateException; -import org.olat.admin.user.groups.AddToGroupsEvent; import org.olat.basesecurity.BaseSecurity; import org.olat.basesecurity.BaseSecurityManager; import org.olat.basesecurity.Constants; @@ -43,6 +42,7 @@ import org.olat.collaboration.CollaborationToolsFactory; import org.olat.commons.lifecycle.LifeCycleManager; import org.olat.core.commons.persistence.DBFactory; import org.olat.core.commons.taskExecutor.TaskExecutorManager; +import org.olat.core.gui.translator.Translator; import org.olat.core.id.Identity; import org.olat.core.logging.DBRuntimeException; import org.olat.core.logging.KnownIssueException; @@ -70,6 +70,7 @@ import org.olat.group.DeletableReference; import org.olat.group.GroupLoggingAction; import org.olat.group.area.BGArea; import org.olat.group.area.BGAreaManager; +import org.olat.group.model.AddToGroupsEvent; import org.olat.group.model.SearchBusinessGroupParams; import org.olat.group.properties.BusinessGroupPropertyManager; import org.olat.group.right.BGRightManager; @@ -115,7 +116,7 @@ public class BusinessGroupServiceImpl implements BusinessGroupService { @Autowired private RepositoryManager repositoryManager; @Autowired - private BusinessGroupAddManager groupAddManager; + private BusinessGroupDeletionManager businessGroupDeletionManager; private List<DeletableGroupData> deleteListeners = new ArrayList<DeletableGroupData>(); @@ -140,6 +141,16 @@ public class BusinessGroupServiceImpl implements BusinessGroupService { public BusinessGroup createBusinessGroup(Identity creator, String name, String description, String type, int minParticipants, int maxParticipants, boolean waitingListEnabled, boolean autoCloseRanksEnabled, OLATResource resource) { + + if(resource != null) { + boolean groupExists = businessGroupDAO.checkIfOneOrMoreNameExistsInContext(Collections.singleton(name), resource); + if (groupExists) { + // there is already a group with this name, return without creating a new group + log.warn("A group with this name already exists! You will get null instead of a businessGroup returned!"); + return null; + } + } + BusinessGroup group = businessGroupDAO.createAndPersist(creator, name, description, type, minParticipants, maxParticipants, waitingListEnabled, autoCloseRanksEnabled); @@ -180,12 +191,6 @@ public class BusinessGroupServiceImpl implements BusinessGroupService { public BusinessGroup mergeBusinessGroup(BusinessGroup group) { return businessGroupDAO.merge(group); } - - @Override - @Transactional - public void updateBusinessGroup(BusinessGroup group) { - businessGroupDAO.update(group); - } @Override @Transactional @@ -196,8 +201,7 @@ public class BusinessGroupServiceImpl implements BusinessGroupService { BusinessGroup reloadedBusinessGroup = loadBusinessGroup(group); reloadedBusinessGroup.setLastUsage(new Date()); LifeCycleManager.createInstanceFor(reloadedBusinessGroup).deleteTimestampFor(SEND_DELETE_EMAIL_ACTION); - updateBusinessGroup(reloadedBusinessGroup); - return reloadedBusinessGroup; + return mergeBusinessGroup(reloadedBusinessGroup); } catch(DBRuntimeException e) { if(e.getCause() instanceof ObjectNotFoundException) { //group deleted @@ -378,6 +382,11 @@ public class BusinessGroupServiceImpl implements BusinessGroupService { public List<Identity> findContacts(Identity identity, int firstResult, int maxResults) { return businessGroupDAO.findContacts(identity, firstResult, maxResults); } + + @Override + public void deleteGroupsAfterLifeCycle(List<BusinessGroup> groups) { + businessGroupDeletionManager.deleteGroups(groups); + } @Override public void deleteBusinessGroup(BusinessGroup group) { @@ -412,6 +421,7 @@ public class BusinessGroupServiceImpl implements BusinessGroupService { // 2) Delete the group areas areaManager.deleteBGtoAreaRelations(group); // 3) Delete the group object itself on the database + businessGroupRelationDAO.deleteRelations(group); businessGroupDAO.delete(group); // 4) Delete the associated security groups if(group.getOwnerGroup() != null) { @@ -452,7 +462,23 @@ public class BusinessGroupServiceImpl implements BusinessGroupService { } } } + + @Override + public List<BusinessGroup> getDeletableGroups(int lastLoginDuration) { + return businessGroupDAO.getDeletableGroups(lastLoginDuration); + } + + @Override + public List<BusinessGroup> getGroupsInDeletionProcess(int deleteEmailDuration) { + return businessGroupDAO.getGroupsInDeletionProcess(deleteEmailDuration); + } + + @Override + public List<BusinessGroup> getGroupsReadyToDelete(int deleteEmailDuration) { + return businessGroupDAO.getGroupsReadyToDelete(deleteEmailDuration); + } + @Override public MailerResult deleteBusinessGroupWithMail(BusinessGroup businessGroupTodelete, String businessPath, Identity deletedBy, Locale locale) { Codepoint.codepoint(this.getClass(), "deleteBusinessGroupWithMail"); @@ -488,6 +514,13 @@ public class BusinessGroupServiceImpl implements BusinessGroupService { } return null; } + + @Override + public String sendDeleteEmailTo(List<BusinessGroup> selectedGroups, MailTemplate mailTemplate, boolean isTemplateChanged, String keyEmailSubject, + String keyEmailBody, Identity sender, Translator pT) { + + return businessGroupDeletionManager.sendDeleteEmailTo(selectedGroups, mailTemplate, isTemplateChanged, keyEmailSubject, keyEmailBody, sender, pT); + } private void removeFromRepositoryEntrySecurityGroup(BusinessGroup group) { /* @@ -699,25 +732,25 @@ public class BusinessGroupServiceImpl implements BusinessGroupService { final BusinessGroupAddResponse response = new BusinessGroupAddResponse(); final BusinessGroup currBusinessGroup = loadBusinessGroup(group); // reload business group - CoordinatorManager.getInstance().getCoordinator().getSyncer().doInSync(currBusinessGroup, new SyncerExecutor(){ - public void execute() { - for (final Identity identity : addIdentities) { - if (securityManager.isIdentityPermittedOnResourceable(identity, Constants.PERMISSION_HASROLE, Constants.ORESOURCE_GUESTONLY)) { - response.getIdentitiesWithoutPermission().add(identity); - } - // Check if identity is already in group. make a db query in case - // someone in another workflow already added this user to this group. if - // found, add user to model - else if (securityManager.isIdentityInSecurityGroup(identity, currBusinessGroup.getWaitingGroup())) { - response.getIdentitiesAlreadyInGroup().add(identity); - } else { - // identity has permission and is not already in group => add it - addToWaitingList(ureqIdentity, identity, currBusinessGroup); - response.getAddedIdentities().add(identity); - log.audit("added identity '" + identity.getName() + "' to securitygroup with key " + currBusinessGroup.getPartipiciantGroup().getKey()); - } + CoordinatorManager.getInstance().getCoordinator().getSyncer().doInSync(currBusinessGroup, new SyncerExecutor(){ + public void execute() { + for (final Identity identity : addIdentities) { + if (securityManager.isIdentityPermittedOnResourceable(identity, Constants.PERMISSION_HASROLE, Constants.ORESOURCE_GUESTONLY)) { + response.getIdentitiesWithoutPermission().add(identity); + } + // Check if identity is already in group. make a db query in case + // someone in another workflow already added this user to this group. if + // found, add user to model + else if (securityManager.isIdentityInSecurityGroup(identity, currBusinessGroup.getWaitingGroup())) { + response.getIdentitiesAlreadyInGroup().add(identity); + } else { + // identity has permission and is not already in group => add it + addToWaitingList(ureqIdentity, identity, currBusinessGroup); + response.getAddedIdentities().add(identity); + log.audit("added identity '" + identity.getName() + "' to securitygroup with key " + currBusinessGroup.getPartipiciantGroup().getKey()); } - }}); + } + }}); return response; } @@ -816,16 +849,73 @@ public class BusinessGroupServiceImpl implements BusinessGroupService { } @Override - public String[] addIdentityToGroups(AddToGroupsEvent groupsEv, Identity ident, Identity addingIdentity) { - return groupAddManager.addIdentityToGroups(groupsEv, ident, addingIdentity); - } + public String[] addIdentityToGroups(final AddToGroupsEvent groupsEv, final Identity ident, final Identity addingIdentity) { + final BGConfigFlags flags = BGConfigFlags.createBuddyGroupDefaultFlags(); + String[] resultTextArgs = new String[2]; + boolean addToAnyGroup = false; - @Override - public String[] addIdentityToGroups(List<Long> ownGroups, List<Long> partGroups, List<Long> mailGroups, Identity ident, - Identity addingIdentity) { - return groupAddManager.addIdentityToGroups(ownGroups, partGroups, mailGroups, ident, addingIdentity); + // notify user about add for following groups: + List<Long> notifyAboutAdd = new ArrayList<Long>(); + List<Long> mailKeys = groupsEv.getMailForGroupsList(); + + // add to owner groups + List<Long> ownerKeys = groupsEv.getOwnerGroupKeys(); + String ownerGroupnames = ""; + + List<BusinessGroup> groups = loadBusinessGroups(ownerKeys); + for (BusinessGroup group : groups) { + if (group != null && !securityManager.isIdentityInSecurityGroup(ident, group.getOwnerGroup())){ +// seems not to work, but would be the way to go! +// ThreadLocalUserActivityLogger.addLoggingResourceInfo(LoggingResourceable.wrap(group)); + addOwner(addingIdentity, ident, group, flags); + ownerGroupnames += group.getName() + ", "; + addToAnyGroup = true; + if (!notifyAboutAdd.contains(group.getKey()) && mailKeys.contains(group.getKey())) notifyAboutAdd.add(group.getKey()); + } + } + resultTextArgs[0] = ownerGroupnames.substring(0, ownerGroupnames.length() > 0 ? ownerGroupnames.length() - 2 : 0); + + // add to participant groups + List<Long> participantKeys = groupsEv.getParticipantGroupKeys(); + String participantGroupnames = ""; + List<BusinessGroup> participantGroups = loadBusinessGroups(participantKeys); + for (BusinessGroup group : participantGroups) { + if (group != null && !securityManager.isIdentityInSecurityGroup(ident, group.getPartipiciantGroup())) { + final BusinessGroup toAddGroup = group; +// seems not to work, but would be the way to go! +// ThreadLocalUserActivityLogger.addLoggingResourceInfo(LoggingResourceable.wrap(group)); + CoordinatorManager.getInstance().getCoordinator().getSyncer().doInSync(group, new SyncerExecutor(){ + public void execute() { + addParticipant(addingIdentity, ident, toAddGroup, flags); + }}); + participantGroupnames += group.getName() + ", "; + addToAnyGroup = true; + if (!notifyAboutAdd.contains(group.getKey()) && mailKeys.contains(group.getKey())) notifyAboutAdd.add(group.getKey()); + } + } + resultTextArgs[1] = participantGroupnames.substring(0, participantGroupnames.length() > 0 ? participantGroupnames.length() - 2 : 0); + + // send notification mails + + List<BusinessGroup> notifGroups = loadBusinessGroups(notifyAboutAdd); + for (BusinessGroup group : notifGroups) { + MailTemplate mailTemplate = BGMailHelper.createAddParticipantMailTemplate(group, addingIdentity); + MailerWithTemplate mailer = MailerWithTemplate.getInstance(); + MailerResult mailerResult = mailer.sendMail(null, ident, null, null, mailTemplate, null); + if (mailerResult.getReturnCode() != MailerResult.OK){ + log.debug("Problems sending Group invitation mail for identity: " + ident.getName() + " and group: " + + group.getName() + " key: " + group.getKey() + " mailerresult: " + mailerResult.getReturnCode(), null); + } + } + + if (addToAnyGroup) { + return resultTextArgs; + } else { + return null; + } } + private void transferFirstIdentityFromWaitingToParticipant(Identity ureqIdentity, BusinessGroup group, BGConfigFlags flags) { CoordinatorManager.getInstance().getCoordinator().getSyncer().assertAlreadyDoInSyncFor(group); // Check if waiting-list is enabled and auto-rank-up @@ -982,14 +1072,12 @@ public class BusinessGroupServiceImpl implements BusinessGroupService { @Transactional(readOnly=true) public boolean isIdentityInBusinessGroup(Identity identity, String groupName, String groupType, boolean ownedById, boolean attendedById, OLATResource resource) { - return businessGroupDAO.isIdentityInBusinessGroup(identity, groupName, groupType, resource); + return businessGroupDAO.isIdentityInBusinessGroup(identity, groupName, resource); } - @Override public void exportGroups(List<BusinessGroup> groups, File fExportFile) { - // TODO Auto-generated method stub - + businessGroupImportExport.exportGroups(groups, fExportFile); } @Override @@ -999,13 +1087,7 @@ public class BusinessGroupServiceImpl implements BusinessGroupService { @Override public void archiveGroups(List<BusinessGroup> groups, File exportFile) { - // TODO Auto-generated method stub - businessGroupArchiver.archiveBGContext(null, exportFile); - } - - @Override - public File archiveAreaMembers(OLATResource resource, List<String> columnList, List<BGArea> areaList, String archiveType, Locale locale, String charset) { - return businessGroupArchiver.archiveAreaMembers(resource, columnList, areaList, archiveType, locale, charset); + businessGroupArchiver.archiveGroups(groups, exportFile); } @Override diff --git a/src/main/java/org/olat/admin/user/groups/AddToGroupsEvent.java b/src/main/java/org/olat/group/model/AddToGroupsEvent.java similarity index 94% rename from src/main/java/org/olat/admin/user/groups/AddToGroupsEvent.java rename to src/main/java/org/olat/group/model/AddToGroupsEvent.java index a811d041cd89f35cdc24cae462c157910a42d9e9..73d21444da9bec225b279fd5cd88ef365ff980c9 100644 --- a/src/main/java/org/olat/admin/user/groups/AddToGroupsEvent.java +++ b/src/main/java/org/olat/group/model/AddToGroupsEvent.java @@ -17,7 +17,7 @@ * frentix GmbH, http://www.frentix.com * <p> */ -package org.olat.admin.user.groups; +package org.olat.group.model; import java.util.List; @@ -34,6 +34,8 @@ import org.olat.core.gui.control.Event; */ public class AddToGroupsEvent extends Event { + private static final long serialVersionUID = 6173876999047030112L; + private List<Long> ownerList; private List<Long> participantList; private List<Long> mailForGroupsList; diff --git a/src/main/java/org/olat/group/ui/edit/BusinessGroupEditController.java b/src/main/java/org/olat/group/ui/edit/BusinessGroupEditController.java index 9e95037e858011b8c2e20e9943600ee868210816..07b3eccbcff9c4a1375d0f74f9acfa5b11c92325 100644 --- a/src/main/java/org/olat/group/ui/edit/BusinessGroupEditController.java +++ b/src/main/java/org/olat/group/ui/edit/BusinessGroupEditController.java @@ -379,7 +379,7 @@ public class BusinessGroupEditController extends BasicController implements Cont if (event == Event.DONE_EVENT) { // update business group with the specified values // values are taken from the modifyBusinessGroupForm - updateBusinessGroup(); + currBusinessGroup = updateBusinessGroup(); // inform index about change refreshAllTabs(ureq); // notify current active users of this business group @@ -418,9 +418,9 @@ public class BusinessGroupEditController extends BasicController implements Cont * persist the updates */ //TODO gm - private void updateBusinessGroup() { + private BusinessGroup updateBusinessGroup() { final BusinessGroup businessGroup = currBusinessGroup; - currBusinessGroup = CoordinatorManager.getInstance().getCoordinator().getSyncer().doInSync(businessGroup, new SyncerCallback<BusinessGroup>() { + return CoordinatorManager.getInstance().getCoordinator().getSyncer().doInSync(businessGroup, new SyncerCallback<BusinessGroup>() { public BusinessGroup execute() { // refresh group to prevent stale object exception and context proxy issues BusinessGroup bg = businessGroupService.loadBusinessGroup(businessGroup); diff --git a/src/main/java/org/olat/group/ui/management/BGManagementController.java b/src/main/java/org/olat/group/ui/management/BGManagementController.java index 0772a0ce3569e8b02464a65546559fceec036a2c..7e6f45dc63a41800780f97054e531f2740b28777 100644 --- a/src/main/java/org/olat/group/ui/management/BGManagementController.java +++ b/src/main/java/org/olat/group/ui/management/BGManagementController.java @@ -921,19 +921,19 @@ public class BGManagementController extends MainLayoutBasicController implements } private void doGroupRun(UserRequest ureq) { - BGControllerFactory.getInstance().createRunControllerAsTopNavTab(this.currentGroup, ureq, getWindowControl(), true); + BGControllerFactory.getInstance().createRunControllerAsTopNavTab(currentGroup, ureq, getWindowControl(), true); } private void doGroupDelete() { // remove this controller as listener from the group - CoordinatorManager.getInstance().getCoordinator().getEventBus().deregisterFor(this, this.currentGroup); + CoordinatorManager.getInstance().getCoordinator().getEventBus().deregisterFor(this, currentGroup); // now delete group and update table model - businessGroupService.deleteBusinessGroup(this.currentGroup); + businessGroupService.deleteBusinessGroup(currentGroup); if (groupListModel != null) { - groupListModel.getObjects().remove(this.currentGroup); + groupListModel.getObjects().remove(currentGroup); groupListCtr.modelChanged(); } - this.currentGroup = null; + currentGroup = null; } private void doGroupList(UserRequest ureq, boolean initializeModel) { diff --git a/src/main/java/org/olat/group/ui/wizard/MemberListWizardController.java b/src/main/java/org/olat/group/ui/wizard/MemberListWizardController.java index 1e67fcb06b28237431291d4988a871e7cf42085d..dae420751b0dd5f5d0cae447fa9a8283ff470a4f 100644 --- a/src/main/java/org/olat/group/ui/wizard/MemberListWizardController.java +++ b/src/main/java/org/olat/group/ui/wizard/MemberListWizardController.java @@ -55,8 +55,6 @@ import org.olat.group.BusinessGroup; import org.olat.group.BusinessGroupService; import org.olat.group.area.BGArea; import org.olat.group.area.BGAreaManager; -import org.olat.group.area.BGAreaManagerImpl; -import org.olat.group.manager.BusinessGroupArchiver; import org.olat.resource.OLATResource; import org.olat.user.UserManager; import org.olat.user.propertyhandlers.UserPropertyHandler; @@ -225,11 +223,9 @@ public class MemberListWizardController extends BasicController { List<Object[]> objectArrays = new ArrayList<Object[]>(); if (GROUPS_MEMBERS.equals(wizardType)) { List<BusinessGroup> groups = businessGroupService.findBusinessGroups(null, null, false, false, resource, 0, -1); - Collections.sort(groups, new Comparator() { + Collections.sort(groups, new Comparator<BusinessGroup>() { @Override - public int compare(Object o1, Object o2) { - BusinessGroup g1 = (BusinessGroup) o1; - BusinessGroup g2 = (BusinessGroup) o2; + public int compare(BusinessGroup g1, BusinessGroup g2) { return g1.getName().compareTo(g2.getName()); } }); @@ -241,16 +237,13 @@ public class MemberListWizardController extends BasicController { } } else if (AREAS_MEMBERS.equals(wizardType)) { List<BGArea> areas = areaManager.findBGAreasOfBGContext(resource); - Collections.sort(areas, new Comparator() { + Collections.sort(areas, new Comparator<BGArea>() { @Override - public int compare(Object o1, Object o2) { - BGArea a1 = (BGArea) o1; - BGArea a2 = (BGArea) o2; + public int compare(BGArea a1, BGArea a2) { return a1.getName().compareTo(a2.getName()); } }); - for (Iterator iter = areas.iterator(); iter.hasNext();) { - BGArea area = (BGArea) iter.next(); + for (BGArea area:areas) { Object[] groupChoiceRowData = new Object[2]; groupChoiceRowData[0] = new Boolean(true); groupChoiceRowData[1] = new ObjectWrapper(area); @@ -268,7 +261,7 @@ public class MemberListWizardController extends BasicController { // wizard steps events if (source == groupsOrAreaChoice) { if (event == Choice.EVNT_VALIDATION_OK) { - List selRows = groupsOrAreaChoice.getSelectedRows(); + List<Integer> selRows = groupsOrAreaChoice.getSelectedRows(); if (selRows.size() == 0) { if (GROUPS_MEMBERS.equals(wizardType)) { this.showError("error.selectatleastonegroup"); @@ -363,7 +356,7 @@ public class MemberListWizardController extends BasicController { if(GROUPS_MEMBERS.equals(wizardType)) { outputFile = businessGroupService.archiveGroupMembers(resource, columnList, groupList, archiveType, userLocale, charset); } else if(AREAS_MEMBERS.equals(wizardType)) { - outputFile = businessGroupService.archiveAreaMembers(resource, columnList, areaList, archiveType, userLocale, charset); + outputFile = areaManager.archiveAreaMembers(resource, columnList, areaList, archiveType, userLocale, charset); } return outputFile; } @@ -375,8 +368,8 @@ public class MemberListWizardController extends BasicController { * @return a list with the selected values of the input choice component. */ private List getSelectedValues(Choice choice) { - List selValues = new ArrayList(); - List selRowsIndexes = choice.getSelectedRows(); + List<Object> selValues = new ArrayList<Object>(); + List<Integer> selRowsIndexes = choice.getSelectedRows(); int numRows = choice.getTableDataModel().getRowCount(); for(int i=0; i<numRows; i++) { if(selRowsIndexes.size() == 0) { @@ -399,7 +392,7 @@ public class MemberListWizardController extends BasicController { */ private void syncTableModelWithSelection(Choice choice) { GenericObjectArrayTableDataModel tableDataModel = (GenericObjectArrayTableDataModel)choice.getTableDataModel(); - List removedRowsIndexes = choice.getRemovedRows(); + List<Integer> removedRowsIndexes = choice.getRemovedRows(); if(removedRowsIndexes.size()>0) { int numRows = choice.getTableDataModel().getRowCount(); for(int i=0; i<numRows; i++) { @@ -485,9 +478,5 @@ public class MemberListWizardController extends BasicController { public Object getWrappedObj() { return wrappedObj; } - public void setWrappedObj(Object wrappedObj) { - this.wrappedObj = wrappedObj; - } } - } diff --git a/src/main/java/org/olat/portfolio/manager/EPStructureManager.java b/src/main/java/org/olat/portfolio/manager/EPStructureManager.java index 79fed0e5cf4ae8859386b5e16ed3664132e9ca12..91f4c90b0637af73564fb4399f8ac230658d9414 100755 --- a/src/main/java/org/olat/portfolio/manager/EPStructureManager.java +++ b/src/main/java/org/olat/portfolio/manager/EPStructureManager.java @@ -1256,7 +1256,7 @@ public class EPStructureManager extends BasicManager { } } - dbInstance.updateObject(targetEl); + targetEl = dbInstance.getCurrentEntityManager().merge(targetEl); } private int indexOf(List<EPStructureToStructureLink> refLinks, EPStructureToStructureLink link, Comparator<EPStructureToStructureLink> comparator) { diff --git a/src/main/java/org/olat/properties/PropertyManager.java b/src/main/java/org/olat/properties/PropertyManager.java index 523a19716dc4c95a1cd44eb054eb3b22a85318d1..c6386d5dd9605ea95907434ba406a0f3a8a3aa77 100644 --- a/src/main/java/org/olat/properties/PropertyManager.java +++ b/src/main/java/org/olat/properties/PropertyManager.java @@ -412,7 +412,7 @@ public class PropertyManager extends BasicManager implements UserDataDeletable { * be ignored in the query * @return List of identities */ - public List findIdentitiesWithProperty(OLATResourceable resourceable, String category, String name, boolean matchNullValues) { + public List<Identity> findIdentitiesWithProperty(OLATResourceable resourceable, String category, String name, boolean matchNullValues) { if (resourceable == null) return findIdentitiesWithProperty(null, null, category, name, matchNullValues); else @@ -430,7 +430,7 @@ public class PropertyManager extends BasicManager implements UserDataDeletable { * be ignored in the query * @return List of identities */ - public List findIdentitiesWithProperty(String resourceTypeName, Long resourceTypeId, String category, String name, boolean matchNullValues) { + public List<Identity> findIdentitiesWithProperty(String resourceTypeName, Long resourceTypeId, String category, String name, boolean matchNullValues) { StringBuilder query = new StringBuilder(); ArrayList objs = new ArrayList(); ArrayList types = new ArrayList(); @@ -587,7 +587,7 @@ public class PropertyManager extends BasicManager implements UserDataDeletable { /** * @return a list of all available resource type names */ - public List getAllResourceTypeNames() { + public List<String> getAllResourceTypeNames() { return DBFactory.getInstance().find("select distinct v.resourceTypeName from org.olat.properties.Property as v where v.resourceTypeName is not null"); } diff --git a/src/main/java/org/olat/resource/OLATResourceManager.java b/src/main/java/org/olat/resource/OLATResourceManager.java index 71de0011a0e0ad69a98dda0552f7e0fd7217e99e..a3e5387520068d367e7807495b88959fa568e593 100644 --- a/src/main/java/org/olat/resource/OLATResourceManager.java +++ b/src/main/java/org/olat/resource/OLATResourceManager.java @@ -72,6 +72,12 @@ public class OLATResourceManager extends BasicManager { return new OLATResourceImpl(resource); } + public OLATResource createAndPersistOLATResourceInstance(OLATResourceable resource) { + OLATResource r = new OLATResourceImpl(resource); + saveOLATResource(r); + return r; + } + /** * Creates a new OLATResource instance (but does not persist the instance) * @param typeName diff --git a/src/main/java/org/olat/restapi/repository/course/CourseGroupWebService.java b/src/main/java/org/olat/restapi/repository/course/CourseGroupWebService.java index 9648220f87bdc9879c59cdb69adf98824d7ce526..a974dc521a2753dcb6c5d615f4ee155e837d7f1a 100644 --- a/src/main/java/org/olat/restapi/repository/course/CourseGroupWebService.java +++ b/src/main/java/org/olat/restapi/repository/course/CourseGroupWebService.java @@ -310,10 +310,10 @@ public class CourseGroupWebService { * @param integer * @return value bigger or equal than 0 */ - private Integer normalize(Integer integer) { + private int normalize(Integer integer) { //fxdiff FXOLAT-122: course management - if(integer == null) return null; - if(integer.intValue() < 0) return null; - return integer; + if(integer == null) return -1; + if(integer.intValue() < 0) return -1; + return integer.intValue(); } } diff --git a/src/main/resources/database/mysql/alter_8_1_x_to_8_2_0.sql b/src/main/resources/database/mysql/alter_8_1_x_to_8_2_0.sql index 9bd2105499c238edc45dcf68ab97deb6d7c0c79e..33f5cd1567956ae0165636638232d93deaccfb06 100644 --- a/src/main/resources/database/mysql/alter_8_1_x_to_8_2_0.sql +++ b/src/main/resources/database/mysql/alter_8_1_x_to_8_2_0.sql @@ -13,4 +13,7 @@ alter table o_gp_business_to_resource add constraint idx_bgp_to_rsrc_group forei alter table o_gp_bgarea add column fk_resource bigint default null; -alter table o_gp_bgarea add constraint idx_area_to_resource foreign key (fk_resource) references o_olatresource (resource_id); \ No newline at end of file +alter table o_gp_bgarea add constraint idx_area_to_resource foreign key (fk_resource) references o_olatresource (resource_id); + +alter table o_gp_bgarea modify groupcontext_fk bigint; + diff --git a/src/main/resources/database/mysql/setupDatabase.sql b/src/main/resources/database/mysql/setupDatabase.sql index cd4464a96d9df2af506efd3549572300903c7ff5..c740ffeab46fa79d7e6c3af54b69537d38d65751 100644 --- a/src/main/resources/database/mysql/setupDatabase.sql +++ b/src/main/resources/database/mysql/setupDatabase.sql @@ -48,6 +48,14 @@ create table if not exists o_gp_business ( fk_waitinggroup bigint unique, primary key (group_id) ); +create table if not exists o_gp_business_to_resource ( + g_id bigint not null, + version mediumint unsigned not null, + creationdate datetime, + fk_resource bigint not null, + fk_group bigint not null, + primary key (g_id) +); create table if not exists o_temporarykey ( reglist_id bigint not null, version mediumint unsigned not null, @@ -277,7 +285,8 @@ create table if not exists o_gp_bgarea ( creationdate datetime, name varchar(255) not null, descr longtext, - groupcontext_fk bigint not null, + groupcontext_fk bigint, + fk_resource bigint default null, primary key (area_id) ); create table if not exists o_repositoryentry ( @@ -1128,6 +1137,8 @@ create index gp_type_idx on o_gp_business (businessgrouptype); alter table o_gp_business add index FKCEEB8A86DF6BCD14 (groupcontext_fk), add constraint FKCEEB8A86DF6BCD14 foreign key (groupcontext_fk) references o_gp_bgcontext (groupcontext_id); alter table o_gp_business add index FKCEEB8A86A1FAC766 (fk_ownergroup), add constraint FKCEEB8A86A1FAC766 foreign key (fk_ownergroup) references o_bs_secgroup (id); alter table o_gp_business add index FKCEEB8A86C06E3EF3 (fk_partipiciantgroup), add constraint FKCEEB8A86C06E3EF3 foreign key (fk_partipiciantgroup) references o_bs_secgroup (id); +alter table o_gp_business_to_resource add constraint idx_bgp_to_rsrc_rsrc foreign key (fk_resource) references o_olatresource (resource_id); +alter table o_gp_business_to_resource add constraint idx_bgp_to_rsrc_group foreign key (fk_group) references o_gp_business (group_id); create index provider_idx on o_bs_authentication (provider); create index credential_idx on o_bs_authentication (credential); create index authusername_idx on o_bs_authentication (authusername); @@ -1178,6 +1189,7 @@ alter table o_bs_policy add index FK9A1C5109F9C3F1D (oresource_id), add constrai alter table o_bs_policy add index FK9A1C5101E2E76DB (group_id), add constraint FK9A1C5101E2E76DB foreign key (group_id) references o_bs_secgroup (id); create index name_idx on o_gp_bgarea (name); alter table o_gp_bgarea add index FK9EFAF698DF6BCD14 (groupcontext_fk), add constraint FK9EFAF698DF6BCD14 foreign key (groupcontext_fk) references o_gp_bgcontext (groupcontext_id); +alter table o_gp_bgarea add constraint idx_area_to_resource foreign key (fk_resource) references o_olatresource (resource_id); create index access_idx on o_repositoryentry (accesscode); create index initialAuthor_idx on o_repositoryentry (initialauthor); create index resource_idx on o_repositoryentry (resourcename); diff --git a/src/main/resources/ehcache.xml b/src/main/resources/ehcache.xml index 6bd45e09ca144491a3312e58aa6f551e749a28d3..d08ee2a4cf19c4cb916e26ae7b62d416145a9180 100644 --- a/src/main/resources/ehcache.xml +++ b/src/main/resources/ehcache.xml @@ -1,4 +1,4 @@ -<ehcache> +<ehcache updateCheck="false"> <!-- OLAT uses ehcache as following: - hibernate second level cache diff --git a/src/test/java/org/olat/commons/coordinate/cluster/jms/JMSTest.java b/src/test/java/org/olat/commons/coordinate/cluster/jms/JMSTest.java index 5c38b40250ed7483e046628f2929cc0bfe82d745..a80c43c0b91c875c3d49862863ec9e932f13100e 100644 --- a/src/test/java/org/olat/commons/coordinate/cluster/jms/JMSTest.java +++ b/src/test/java/org/olat/commons/coordinate/cluster/jms/JMSTest.java @@ -28,6 +28,8 @@ package org.olat.commons.coordinate.cluster.jms; import static org.junit.Assert.assertNotNull; +import java.util.UUID; + import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -45,6 +47,7 @@ import org.olat.core.util.event.EventBus; import org.olat.core.util.event.GenericEventListener; import org.olat.core.util.event.MultiUserEvent; import org.olat.core.util.resource.OresHelper; +import org.olat.test.JunitTestHelper; import org.olat.test.OlatTestCase; /** @@ -55,38 +58,39 @@ import org.olat.test.OlatTestCase; public class JMSTest extends OlatTestCase { private static boolean isInitialized = false; private static Identity id1; - private OLATResourceable ores1; - - private Event event = null; - + private Event event; - @Before public void setup() throws Exception { + @Before + public void setup() throws Exception { if (isInitialized == false) { - //ident = JunitTestHelper.createAndPersistIdentityAsUser("anIdentity"); - id1 = BaseSecurityManager.getInstance().createAndPersistIdentity("id1", null, BaseSecurityModule.getDefaultAuthProviderIdentifier(), "id1", - Encoder.encrypt("id1")); + id1 = JunitTestHelper.createAndPersistIdentityAsUser("jms" + UUID.randomUUID().toString()); DBFactory.getInstance().closeSession(); isInitialized = true; } } + + @After + public void tearDown() throws Exception { + DBFactory.getInstance().closeSession(); + } /** * */ - @Test public void testSendReceive() { + @Test + public void testSendReceive() { // enable test only if we have the cluster configuration enabled. // this test requires that an JMS Provider is running // (see file serviceconfig/org/olat/core/_spring/coreextconfig.xml) EventBus bus = CoordinatorManager.getInstance().getCoordinator().getEventBus(); if (bus instanceof ClusterEventBus) { // send and wait some time until a message should arrive at the latest. - ores1 = OresHelper.createOLATResourceableInstance("hellojms", new Long(123)); + OLATResourceable ores1 = OresHelper.createOLATResourceableInstance("hellojms", new Long(123)); bus.registerFor(new GenericEventListener(){ public void event(Event event) { - // TODO Auto-generated method stub System.out.println("event received!"+event); JMSTest.this.event = event; }}, id1, ores1); @@ -97,17 +101,10 @@ public class JMSTest extends OlatTestCase { try { Thread.sleep(2000); } catch (InterruptedException e) { - // TODO Auto-generated catch block e.printStackTrace(); } assertNotNull("after 2 secs, an answer from the jms should have arrived", event); - } // else no tests to pass here } - - @After public void tearDown() throws Exception { - DBFactory.getInstance().closeSession(); - } - } \ No newline at end of file diff --git a/src/test/java/org/olat/commons/lifecycle/LifeCycleManagerTest.java b/src/test/java/org/olat/commons/lifecycle/LifeCycleManagerTest.java index 2eb5c4fe884c0868569340bfe7108e4796adca9a..0b29399c885ed2bc16aaeb58fe0f0c854e0fe073 100644 --- a/src/test/java/org/olat/commons/lifecycle/LifeCycleManagerTest.java +++ b/src/test/java/org/olat/commons/lifecycle/LifeCycleManagerTest.java @@ -32,16 +32,18 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; -import org.apache.log4j.Logger; +import java.util.UUID; + import org.junit.After; import org.junit.Before; import org.junit.Test; import org.olat.core.commons.persistence.DBFactory; import org.olat.core.id.Identity; -import org.olat.core.id.OLATResourceable; +import org.olat.core.logging.OLog; import org.olat.core.logging.Tracing; import org.olat.group.BusinessGroup; import org.olat.group.BusinessGroupService; +import org.olat.resource.OLATResource; import org.olat.resource.OLATResourceManager; import org.olat.test.JunitTestHelper; import org.olat.test.OlatTestCase; @@ -55,16 +57,13 @@ import org.springframework.beans.factory.annotation.Autowired; * Comment: * */ -public class LifeCycleManagerTest extends OlatTestCase implements OLATResourceable { +public class LifeCycleManagerTest extends OlatTestCase { - private long RESOURCE_ID = 144; - private String RESOURCE_TYPE = "org.olat.commons.lifecycle.LifeCycleManagerTest"; - private static Logger log = Logger.getLogger(LifeCycleManagerTest.class); - private static Identity identity = null; - private static BusinessGroup group = null; - private static org.olat.resource.OLATResource res = null; + private static OLog log = Tracing.createLoggerFor(LifeCycleManagerTest.class); + private static Identity identity; + private static BusinessGroup group; + private static OLATResource res; - @Autowired private BusinessGroupService businessGroupService; @@ -74,20 +73,20 @@ public class LifeCycleManagerTest extends OlatTestCase implements OLATResourceab @Before public void setup() { // identity with null User should be ok for test case - res = OLATResourceManager.getInstance().createOLATResourceInstance(this); - OLATResourceManager.getInstance().saveOLATResource(res); - identity = JunitTestHelper.createAndPersistIdentityAsUser("foo"); - group = businessGroupService.createBusinessGroup( identity, "a buddygroup", "a desc", BusinessGroup.TYPE_BUDDYGROUP, -1, -1, false, false, null); + res = JunitTestHelper.createRandomResource(); + identity = JunitTestHelper.createAndPersistIdentityAsUser("foo-" + UUID.randomUUID().toString()); + group = businessGroupService.createBusinessGroup(identity, "a buddygroup", "a desc", BusinessGroup.TYPE_BUDDYGROUP, -1, -1, false, false, null); } /** * @see junit.framework.TestCase#tearDown() */ - @After public void tearDown() { + @After + public void tearDown() { try { OLATResourceManager.getInstance().deleteOLATResource(res); businessGroupService.deleteBusinessGroup(group); - Tracing.logInfo("tearDown: DB.getInstance().closeSession()", this.getClass()); + log.info("tearDown: DB.getInstance().closeSession()"); DBFactory.getInstance().closeSession(); } catch (Exception e) { log.error("tearDown failed: ", e); @@ -97,7 +96,8 @@ public class LifeCycleManagerTest extends OlatTestCase implements OLATResourceab /** * Test creation of LifeCycleManager. */ - @Test public void testCreateInstanceFor() { + @Test + public void testCreateInstanceFor() { LifeCycleManager lcm1 = LifeCycleManager.createInstanceFor(group); LifeCycleManager lcm2 = LifeCycleManager.createInstanceFor(res); assertNotSame("testCreateInstanceFor should NOT return the same instance", lcm1,lcm2); @@ -106,7 +106,8 @@ public class LifeCycleManagerTest extends OlatTestCase implements OLATResourceab /** * Test: mark two timestamp in different context. */ - @Test public void testMarkTimestampFor() { + @Test + public void testMarkTimestampFor() { String action = "doTest"; LifeCycleManager lcm1 = LifeCycleManager.createInstanceFor(group); LifeCycleManager lcm2 = LifeCycleManager.createInstanceFor(res); @@ -126,7 +127,8 @@ public class LifeCycleManagerTest extends OlatTestCase implements OLATResourceab /** * Test: Delete Timestamp for certain action */ - @Test public void testDeleteTimestampFor() { + @Test + public void testDeleteTimestampFor() { String action = "doTestDelete"; LifeCycleManager lcm1 = LifeCycleManager.createInstanceFor(group); lcm1.markTimestampFor(action); @@ -135,23 +137,5 @@ public class LifeCycleManagerTest extends OlatTestCase implements OLATResourceab lcm1.deleteTimestampFor(action); LifeCycleEntry lce2 = lcm1.lookupLifeCycleEntry(action, null); assertNull("Found deleted LifeCycleEntry", lce2); - - } - - ////////////////////////////// - // Implements OLATResourceable - ////////////////////////////// - /** - * @see org.olat.core.id.OLATResourceablegetResourceableTypeName() - */ - public String getResourceableTypeName() { - return RESOURCE_TYPE; - } - - /** - * @see org.olat.core.id.OLATResourceablegetResourceableId() - */ - public Long getResourceableId() { - return new Long(RESOURCE_ID); } } diff --git a/src/test/java/org/olat/course/assessment/AssessmentManagerTest.java b/src/test/java/org/olat/course/assessment/AssessmentManagerTest.java index 55ee1e0cae5fd6b6ebbda7c0c7781c543a81821a..d080b5c97395c8aade5cc4353225a73a83bb142c 100644 --- a/src/test/java/org/olat/course/assessment/AssessmentManagerTest.java +++ b/src/test/java/org/olat/course/assessment/AssessmentManagerTest.java @@ -44,7 +44,6 @@ import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.olat.core.commons.persistence.DB; import org.olat.core.commons.persistence.DBFactory; import org.olat.core.id.Identity; import org.olat.core.id.IdentityEnvironment; @@ -95,8 +94,7 @@ public class AssessmentManagerTest extends OlatTestCase { RepositoryEntry repositoryEntry = JunitTestHelper.deployDemoCourse(); Long resourceableId = repositoryEntry.getOlatResource().getResourceableId(); System.out.println("Demo course imported - resourceableId: " + resourceableId); - - DB db = DBFactory.getInstance(); + course = CourseFactory.loadCourse(resourceableId); DBFactory.getInstance().closeSession(); @@ -106,14 +104,11 @@ public class AssessmentManagerTest extends OlatTestCase { log.info("setUp done ------------------------"); } catch (RuntimeException e) { log.error("Exception in setUp(): " + e); - e.printStackTrace(); } } + @After - public void tearDown() throws Exception { - // TODO: Does not cleanup Demo-course because other Test which use Demo-Course too, will be have failures - //remove demo course on file system - //CourseFactory.deleteCourse(course); + public void tearDown() throws Exception { try { DBFactory.getInstance().closeSession(); } catch (Exception e) { @@ -233,8 +228,7 @@ public class AssessmentManagerTest extends OlatTestCase { } } } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + log.error("", e); } //delete the efficiencyStatements for the current course diff --git a/src/test/java/org/olat/course/groupsandrights/CourseGroupManagementTest.java b/src/test/java/org/olat/course/groupsandrights/CourseGroupManagementTest.java index eecaa73ea5e869f86748b311ce3875924ecd5ffe..e131d2439cb0cfec716ac2eafb8ce8be4e9eecd3 100644 --- a/src/test/java/org/olat/course/groupsandrights/CourseGroupManagementTest.java +++ b/src/test/java/org/olat/course/groupsandrights/CourseGroupManagementTest.java @@ -29,23 +29,22 @@ package org.olat.course.groupsandrights; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import java.util.UUID; + import org.apache.log4j.Logger; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.olat.basesecurity.BaseSecurity; -import org.olat.basesecurity.BaseSecurityManager; import org.olat.core.commons.persistence.DBFactory; import org.olat.core.id.Identity; -import org.olat.core.id.OLATResourceable; -import org.olat.core.util.resource.OresHelper; import org.olat.group.BusinessGroup; import org.olat.group.BusinessGroupService; import org.olat.group.area.BGArea; import org.olat.group.area.BGAreaManager; import org.olat.group.right.BGRightManager; import org.olat.resource.OLATResource; -import org.olat.resource.OLATResourceManager; import org.olat.test.JunitTestHelper; import org.olat.test.OlatTestCase; import org.springframework.beans.factory.annotation.Autowired; @@ -60,7 +59,6 @@ public class CourseGroupManagementTest extends OlatTestCase { private static Logger log = Logger.getLogger(CourseGroupManagementTest.class.getName()); private Identity id1, id2, id3; - private OLATResource course1; @Autowired private BGRightManager rightManager; @@ -68,138 +66,176 @@ public class CourseGroupManagementTest extends OlatTestCase { private BGAreaManager areaManager; @Autowired private BusinessGroupService businessGroupService; + @Autowired + private BaseSecurity securityManager; + - @Before public void setUp() { try { - id1 = JunitTestHelper.createAndPersistIdentityAsUser("one"); - id2 = JunitTestHelper.createAndPersistIdentityAsUser("twoo"); - id3 = JunitTestHelper.createAndPersistIdentityAsUser("three"); - - OLATResourceManager rm = OLATResourceManager.getInstance(); - // create course and persist as OLATResourceImpl - OLATResourceable resourceable = OresHelper.createOLATResourceableInstance("junitcourse",System.currentTimeMillis()); - course1 = rm.createOLATResourceInstance(resourceable); - DBFactory.getInstance().saveObject(course1); - + id1 = JunitTestHelper.createAndPersistIdentityAsUser(UUID.randomUUID().toString()); + id2 = JunitTestHelper.createAndPersistIdentityAsUser(UUID.randomUUID().toString()); + id3 = JunitTestHelper.createAndPersistIdentityAsUser(UUID.randomUUID().toString()); + DBFactory.getInstance().closeSession(); } catch (Exception e) { log.error("Exception in setUp(): " + e); - e.printStackTrace(); } } - @After public void tearDown() throws Exception { try { - DBFactory.getInstance().closeSession(); - } catch (Exception e) { + DBFactory.getInstance().closeSession(); + } catch (Exception e) { log.error("Exception in tearDown(): " + e); - e.printStackTrace(); - throw e; - } + throw e; + } + } + + /** rights tests */ + @Test + public void testHasRightIsInMethodsByGroups() { + OLATResource course1 = JunitTestHelper.createRandomResource(); + + // create groups without waitinglist + BusinessGroup g1 = businessGroupService.createBusinessGroup(null, "g1", null, BusinessGroup.TYPE_LEARNINGROUP, 0, 10, false, false, + course1); + BusinessGroup g2 = businessGroupService.createBusinessGroup(null, "g2", null, BusinessGroup.TYPE_LEARNINGROUP, 0, 10, false, false, + course1); + // members + securityManager.addIdentityToSecurityGroup(id1, g2.getOwnerGroup()); + securityManager.addIdentityToSecurityGroup(id1, g1.getPartipiciantGroup()); + securityManager.addIdentityToSecurityGroup(id2, g1.getPartipiciantGroup()); + securityManager.addIdentityToSecurityGroup(id2, g2.getPartipiciantGroup()); + securityManager.addIdentityToSecurityGroup(id3, g1.getOwnerGroup()); + + // groups + BusinessGroup g3 = businessGroupService.createBusinessGroup(null, "g3", null, BusinessGroup.TYPE_RIGHTGROUP, -1, -1, false, false, + course1); + BusinessGroup g4 = businessGroupService.createBusinessGroup(null, "g4", null, BusinessGroup.TYPE_RIGHTGROUP, -1, -1, false, false, + course1); + // members + securityManager.addIdentityToSecurityGroup(id1, g3.getPartipiciantGroup()); + securityManager.addIdentityToSecurityGroup(id1, g4.getPartipiciantGroup()); + securityManager.addIdentityToSecurityGroup(id3, g4.getPartipiciantGroup()); + // rights + rightManager.addBGRight(CourseRights.RIGHT_ARCHIVING, g3); + rightManager.addBGRight(CourseRights.RIGHT_COURSEEDITOR, g3); + rightManager.addBGRight(CourseRights.RIGHT_ARCHIVING, g4); + rightManager.addBGRight(CourseRights.RIGHT_GROUPMANAGEMENT, g4); + + DBFactory.getInstance().closeSession(); // simulate user clicks + + // test groups + CourseGroupManager gm = PersistingCourseGroupManager.getInstance(course1); + assertTrue(gm.isIdentityInGroup(id1, g1.getName())); + assertTrue(gm.isIdentityInGroup(id1, g2.getName())); + assertTrue(gm.isIdentityInGroup(id1, g3.getName())); + assertTrue(gm.isIdentityInGroup(id1, g4.getName())); + + assertTrue(gm.isIdentityInGroup(id2, g1.getName())); + assertTrue(gm.isIdentityInGroup(id2, g2.getName())); + assertFalse(gm.isIdentityInGroup(id2, g3.getName())); + assertFalse(gm.isIdentityInGroup(id2, g4.getName())); + + DBFactory.getInstance().closeSession(); + assertTrue(gm.isIdentityInGroup(id3, g1.getName())); + assertFalse(gm.isIdentityInGroup(id3, g2.getName())); + assertFalse(gm.isIdentityInGroup(id3, g3.getName())); + assertTrue(gm.isIdentityInGroup(id3, g4.getName())); + + // test rights + DBFactory.getInstance().closeSession(); + assertTrue(gm.hasRight(id1, CourseRights.RIGHT_ARCHIVING)); + assertTrue(gm.hasRight(id1, CourseRights.RIGHT_COURSEEDITOR)); + assertTrue(gm.hasRight(id1, CourseRights.RIGHT_GROUPMANAGEMENT)); + assertFalse(gm.hasRight(id1, CourseRights.RIGHT_ASSESSMENT)); + assertTrue(gm.hasRight(id1, CourseRights.RIGHT_COURSEEDITOR)); + assertTrue(gm.hasRight(id1, CourseRights.RIGHT_COURSEEDITOR)); + assertFalse(gm.hasRight(id2, CourseRights.RIGHT_COURSEEDITOR)); + + // test context + DBFactory.getInstance().closeSession(); } /** rights tests */ @Test - public void testHasRightIsInMethods() { - BaseSecurity secm = BaseSecurityManager.getInstance(); - - // 1) context one: learning groups - OLATResource c1 = JunitTestHelper.createRandomResource(); - - // create groups without waitinglist - BusinessGroup g1 = businessGroupService.createBusinessGroup(null, "g1", null, BusinessGroup.TYPE_LEARNINGROUP,new Integer(0), new Integer(10), false, false, c1); - BusinessGroup g2 = businessGroupService.createBusinessGroup(null, "g2", null, BusinessGroup.TYPE_LEARNINGROUP, new Integer(0), new Integer(10), false, false, c1); - // members - secm.addIdentityToSecurityGroup(id1, g2.getOwnerGroup()); - secm.addIdentityToSecurityGroup(id1, g1.getPartipiciantGroup()); - secm.addIdentityToSecurityGroup(id2, g1.getPartipiciantGroup()); - secm.addIdentityToSecurityGroup(id2, g2.getPartipiciantGroup()); - secm.addIdentityToSecurityGroup(id3, g1.getOwnerGroup()); - // areas - BGArea a1 = areaManager.createAndPersistBGAreaIfNotExists("a1", "desca1",c1); - BGArea a2 = areaManager.createAndPersistBGAreaIfNotExists("a2", null, c1); - BGArea a3 = areaManager.createAndPersistBGAreaIfNotExists("a3", null, c1); - areaManager.addBGToBGArea(g1, a1); - areaManager.addBGToBGArea(g2, a1); - areaManager.addBGToBGArea(g1, a2); - areaManager.addBGToBGArea(g2, a3); - - // 2) context two: right groups - OLATResource c2 = JunitTestHelper.createRandomResource(); - // groups - BusinessGroup g3 = businessGroupService.createBusinessGroup(null, "g3", null, BusinessGroup.TYPE_RIGHTGROUP, -1, -1, false, false, c2); - BusinessGroup g4 = businessGroupService.createBusinessGroup(null, "g4", null, BusinessGroup.TYPE_RIGHTGROUP, -1, -1, false, false, c2); - // members - secm.addIdentityToSecurityGroup(id1, g3.getPartipiciantGroup()); - secm.addIdentityToSecurityGroup(id1, g4.getPartipiciantGroup()); - secm.addIdentityToSecurityGroup(id3, g4.getPartipiciantGroup()); - // rights - rightManager.addBGRight(CourseRights.RIGHT_ARCHIVING, g3); - rightManager.addBGRight(CourseRights.RIGHT_COURSEEDITOR, g3); - rightManager.addBGRight(CourseRights.RIGHT_ARCHIVING, g4); - rightManager.addBGRight(CourseRights.RIGHT_GROUPMANAGEMENT, g4); - - DBFactory.getInstance().closeSession(); // simulate user clicks - - // test groups - CourseGroupManager gm = PersistingCourseGroupManager.getInstance(course1); - assertTrue(gm.isIdentityInLearningGroup(id1, g1.getName())); - assertTrue(gm.isIdentityInLearningGroup(id1, g2.getName())); - assertFalse(gm.isIdentityInLearningGroup(id1, g3.getName())); // not a learning group - assertFalse(gm.isIdentityInLearningGroup(id1, g4.getName())); // not a learning group - - assertTrue(gm.isIdentityInLearningGroup(id2, g1.getName())); - assertTrue(gm.isIdentityInLearningGroup(id2, g2.getName())); - assertFalse(gm.isIdentityInLearningGroup(id2, g3.getName())); // not a learning group - assertFalse(gm.isIdentityInLearningGroup(id2, g4.getName())); // not a learning group - - DBFactory.getInstance().closeSession(); - assertTrue(gm.isIdentityInLearningGroup(id3, g1.getName())); - assertFalse(gm.isIdentityInLearningGroup(id3, g2.getName())); - assertFalse(gm.isIdentityInLearningGroup(id3, g3.getName())); // not a learning group - assertFalse(gm.isIdentityInLearningGroup(id3, g4.getName())); // not a learning group - - assertTrue(gm.isIdentityInLearningGroup(id1, g1.getName())); - assertFalse(gm.isIdentityInLearningGroup(id1, g1.getName())); - assertTrue(gm.isIdentityInLearningGroup(id3, g1.getName())); - assertFalse(gm.isIdentityInLearningGroup(id3, g1.getName())); - - // test areas - DBFactory.getInstance().closeSession(); - assertTrue(gm.isIdentityInLearningArea(id1, a1.getName())); - assertTrue(gm.isIdentityInLearningArea(id1, a2.getName())); - assertTrue(gm.isIdentityInLearningArea(id1, a3.getName())); - - assertTrue(gm.isIdentityInLearningArea(id2, a1.getName())); - assertTrue(gm.isIdentityInLearningArea(id2, a2.getName())); - assertTrue(gm.isIdentityInLearningArea(id2, a3.getName())); - - DBFactory.getInstance().closeSession(); - assertTrue(gm.isIdentityInLearningArea(id3, a1.getName())); - assertTrue(gm.isIdentityInLearningArea(id3, a2.getName())); - assertFalse(gm.isIdentityInLearningArea(id3, a3.getName())); - - DBFactory.getInstance().closeSession(); - assertTrue(gm.getLearningAreasOfGroupFromAllContexts(g1.getName()).size() == 2); - assertTrue(gm.getLearningAreasOfGroupFromAllContexts(g2.getName()).size() == 2); - - // test rights - DBFactory.getInstance().closeSession(); - assertTrue(gm.hasRight(id1, CourseRights.RIGHT_ARCHIVING)); - assertTrue(gm.hasRight(id1, CourseRights.RIGHT_COURSEEDITOR)); - assertTrue(gm.hasRight(id1, CourseRights.RIGHT_GROUPMANAGEMENT)); - assertFalse(gm.hasRight(id1, CourseRights.RIGHT_ASSESSMENT)); - assertTrue(gm.hasRight(id1, CourseRights.RIGHT_COURSEEDITOR)); - assertFalse(gm.hasRight(id1, CourseRights.RIGHT_COURSEEDITOR)); - assertFalse(gm.hasRight(id2, CourseRights.RIGHT_COURSEEDITOR)); - - // test context - DBFactory.getInstance().closeSession(); + public void testHasRightIsInMethodsByArea() { + OLATResource course1 = JunitTestHelper.createRandomResource(); + + // create groups without waitinglist + BusinessGroup g1 = businessGroupService.createBusinessGroup(null, "g1", null, BusinessGroup.TYPE_LEARNINGROUP, 0, 10, false, false, + course1); + BusinessGroup g2 = businessGroupService.createBusinessGroup(null, "g2", null, BusinessGroup.TYPE_LEARNINGROUP, 0, 10, false, false, + course1); + // members + securityManager.addIdentityToSecurityGroup(id1, g2.getOwnerGroup()); + securityManager.addIdentityToSecurityGroup(id1, g1.getPartipiciantGroup()); + securityManager.addIdentityToSecurityGroup(id2, g1.getPartipiciantGroup()); + securityManager.addIdentityToSecurityGroup(id2, g2.getPartipiciantGroup()); + securityManager.addIdentityToSecurityGroup(id3, g1.getOwnerGroup()); + // areas + BGArea a1 = areaManager.createAndPersistBGAreaIfNotExists("a1", "desca1", course1); + BGArea a2 = areaManager.createAndPersistBGAreaIfNotExists("a2", null, course1); + BGArea a3 = areaManager.createAndPersistBGAreaIfNotExists("a3", null, course1); + areaManager.addBGToBGArea(g1, a1); + areaManager.addBGToBGArea(g2, a1); + areaManager.addBGToBGArea(g1, a2); + areaManager.addBGToBGArea(g2, a3); + + // groups + BusinessGroup g3 = businessGroupService.createBusinessGroup(null, "g3", null, BusinessGroup.TYPE_RIGHTGROUP, -1, -1, false, false, + course1); + BusinessGroup g4 = businessGroupService.createBusinessGroup(null, "g4", null, BusinessGroup.TYPE_RIGHTGROUP, -1, -1, false, false, + course1); + // members + securityManager.addIdentityToSecurityGroup(id1, g3.getPartipiciantGroup()); + securityManager.addIdentityToSecurityGroup(id1, g4.getPartipiciantGroup()); + securityManager.addIdentityToSecurityGroup(id3, g4.getPartipiciantGroup()); + // rights + rightManager.addBGRight(CourseRights.RIGHT_ARCHIVING, g3); + rightManager.addBGRight(CourseRights.RIGHT_COURSEEDITOR, g3); + rightManager.addBGRight(CourseRights.RIGHT_ARCHIVING, g4); + rightManager.addBGRight(CourseRights.RIGHT_GROUPMANAGEMENT, g4); + + DBFactory.getInstance().closeSession(); // simulate user clicks + + // test groups + CourseGroupManager gm = PersistingCourseGroupManager.getInstance(course1); + + // test areas + DBFactory.getInstance().closeSession(); + assertTrue(gm.isIdentityInLearningArea(id1, a1.getName())); + assertTrue(gm.isIdentityInLearningArea(id1, a2.getName())); + assertTrue(gm.isIdentityInLearningArea(id1, a3.getName())); + + assertTrue(gm.isIdentityInLearningArea(id2, a1.getName())); + assertTrue(gm.isIdentityInLearningArea(id2, a2.getName())); + assertTrue(gm.isIdentityInLearningArea(id2, a3.getName())); + + DBFactory.getInstance().closeSession(); + assertTrue(gm.isIdentityInLearningArea(id3, a1.getName())); + assertTrue(gm.isIdentityInLearningArea(id3, a2.getName())); + assertFalse(gm.isIdentityInLearningArea(id3, a3.getName())); + + DBFactory.getInstance().closeSession(); + Assert.assertEquals(2, gm.getLearningAreasOfGroupFromAllContexts(g1.getName()).size()); + Assert.assertEquals(2, gm.getLearningAreasOfGroupFromAllContexts(g2.getName()).size()); + + // test rights + DBFactory.getInstance().closeSession(); + assertTrue(gm.hasRight(id1, CourseRights.RIGHT_ARCHIVING)); + assertTrue(gm.hasRight(id1, CourseRights.RIGHT_COURSEEDITOR)); + assertTrue(gm.hasRight(id1, CourseRights.RIGHT_GROUPMANAGEMENT)); + assertFalse(gm.hasRight(id1, CourseRights.RIGHT_ASSESSMENT)); + assertTrue(gm.hasRight(id1, CourseRights.RIGHT_COURSEEDITOR)); + assertTrue(gm.hasRight(id1, CourseRights.RIGHT_COURSEEDITOR)); + assertFalse(gm.hasRight(id2, CourseRights.RIGHT_COURSEEDITOR)); + + // test context + DBFactory.getInstance().closeSession(); } } \ No newline at end of file diff --git a/src/test/java/org/olat/course/nodes/projectbroker/ProjectBrokerManagerTest.java b/src/test/java/org/olat/course/nodes/projectbroker/ProjectBrokerManagerTest.java index 6e3865085fd86c89dafbdd8814245403448e2004..afd1adbccb616b676d0051f2666b4900d183cb52 100644 --- a/src/test/java/org/olat/course/nodes/projectbroker/ProjectBrokerManagerTest.java +++ b/src/test/java/org/olat/course/nodes/projectbroker/ProjectBrokerManagerTest.java @@ -40,6 +40,8 @@ import java.util.Date; import java.util.List; import java.util.Locale; +import junit.framework.Assert; + import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; @@ -124,13 +126,15 @@ public class ProjectBrokerManagerTest extends OlatTestCase { DBFactory.getInstance().closeSession(); // get project list and check content List<Project> projectListA = ProjectBrokerManagerFactory.getProjectBrokerManager().getProjectListBy(idProjectBrokerA); - List<Project> projectListB = ProjectBrokerManagerFactory.getProjectBrokerManager().getProjectListBy(idProjectBrokerB); assertEquals("Wrong projectList.size for project-broker A",2, projectListA.size()); - assertEquals("Wrong projectList.size for project-broker B",2, projectListB.size()); assertTrue("Wrong thema in project list A, title must start with 'thema A'", projectListA.get(0).getTitle().startsWith("thema A")); assertTrue("Wrong thema in project list A, title must start with 'thema A'", projectListA.get(1).getTitle().startsWith("thema A")); + + List<Project> projectListB = ProjectBrokerManagerFactory.getProjectBrokerManager().getProjectListBy(idProjectBrokerB); + assertEquals("Wrong projectList.size for project-broker B",2, projectListB.size()); assertTrue("Wrong thema in project list B, title must start with 'thema B'", projectListB.get(0).getTitle().startsWith("thema B")); assertTrue("Wrong thema in project list B, title must start with 'thema B'", projectListB.get(1).getTitle().startsWith("thema B")); + if (projectListA.get(0).getTitle().equals("thema A1")) { assertTrue("Wrong thema in project list A, title must be 'thema A2'", projectListA.get(1).getTitle().equals("thema A2")); } else if (projectListA.get(0).getTitle().equals("thema A2")) { @@ -235,7 +239,7 @@ public class ProjectBrokerManagerTest extends OlatTestCase { for (int i = 0; i < ITERATION; i++) { createProject("thema D1_" + i, id1, idProjectBrokerD, resourceableId ); } - List projectListD = ProjectBrokerManagerFactory.getProjectBrokerManager().getProjectListBy(idProjectBrokerD); + List<Project> projectListD = ProjectBrokerManagerFactory.getProjectBrokerManager().getProjectListBy(idProjectBrokerD); ProjectListTableModel tableModel = new ProjectListTableModel(projectListD, id1, translator, moduleConfig, 0, 0, 0, false); // loop over table like rendering loop @@ -243,6 +247,7 @@ public class ProjectBrokerManagerTest extends OlatTestCase { for (int row = START_PAGE_INDEX; row < START_PAGE_INDEX+PAGE_SIZE; row++) { for (int col = 0; col < tableModel.getColumnCount(); col++) { Object element = tableModel.getValueAt(row, col); + Assert.assertNotNull(element); } } long endTime = System.currentTimeMillis(); diff --git a/src/test/java/org/olat/group/BusinessGroupTest.java b/src/test/java/org/olat/group/BusinessGroupTest.java deleted file mode 100644 index 6fa73d9b859fc5cd0a5ac214e49409cd1ff63546..0000000000000000000000000000000000000000 --- a/src/test/java/org/olat/group/BusinessGroupTest.java +++ /dev/null @@ -1,432 +0,0 @@ -/** -* OLAT - Online Learning and Training<br> -* http://www.olat.org -* <p> -* Licensed under the Apache License, Version 2.0 (the "License"); <br> -* you may not use this file except in compliance with the License.<br> -* You may obtain a copy of the License at -* <p> -* http://www.apache.org/licenses/LICENSE-2.0 -* <p> -* Unless required by applicable law or agreed to in writing,<br> -* software distributed under the License is distributed on an "AS IS" BASIS, <br> -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> -* See the License for the specific language governing permissions and <br> -* limitations under the License. -* <p> -* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> -* University of Zurich, Switzerland. -* <hr> -* <a href="http://www.openolat.org"> -* OpenOLAT - Online Learning and Training</a><br> -* This file has been modified by the OpenOLAT community. Changes are licensed -* under the Apache 2.0 license as the original file. -* <p> -*/ - -package org.olat.group; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.List; - -import org.apache.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.olat.basesecurity.BaseSecurity; -import org.olat.basesecurity.BaseSecurityManager; -import org.olat.basesecurity.Policy; -import org.olat.basesecurity.SecurityGroup; -import org.olat.core.commons.persistence.DB; -import org.olat.core.commons.persistence.DBFactory; -import org.olat.core.id.Identity; -import org.olat.core.id.OLATResourceable; -import org.olat.core.logging.AssertException; -import org.olat.core.util.resource.OresHelper; -import org.olat.course.groupsandrights.CourseRights; -import org.olat.group.context.BGContext; -import org.olat.group.context.BGContextManagerImpl; -import org.olat.group.right.BGRightManager; -import org.olat.resource.OLATResource; -import org.olat.resource.OLATResourceManager; -import org.olat.test.JunitTestHelper; -import org.olat.test.OlatTestCase; -import org.springframework.beans.factory.annotation.Autowired; - -/** - * Description:<BR> - * Initial Date: Aug 18, 2004 - * - * @author gnaegi - */ -public class BusinessGroupTest extends OlatTestCase { - - private static Logger log = Logger.getLogger(BusinessGroupTest.class.getName()); - private Identity id1, id2, id3, id4; - private static OLATResource course1 = null; - - @Autowired - private BusinessGroupService businessGroupService; - @Autowired - private BGRightManager rightManager; - - /** - * SetUp is called before each test. - */ - @Before - public void setUp() { - try { - id1 = JunitTestHelper.createAndPersistIdentityAsUser("one"); - id2 = JunitTestHelper.createAndPersistIdentityAsUser("twoo"); - id3 = JunitTestHelper.createAndPersistIdentityAsUser("three"); - id4 = JunitTestHelper.createAndPersistIdentityAsUser("four"); - - if (course1 == null) { - DB db = DBFactory.getInstance(); - OLATResourceManager rm = OLATResourceManager.getInstance(); - // create course and persist as OLATResourceImpl - OLATResourceable resourceable = OresHelper.createOLATResourceableInstance("junitcourse", new Long(456)); - course1 = rm.createOLATResourceInstance(resourceable); - db.saveObject(course1); - - DBFactory.getInstance().closeSession(); - } - } catch (Exception e) { - log.error("Exception in setUp(): " + e); - e.printStackTrace(); - } - } - - /** - * TearDown is called after each test. - * - * @throws Exception - */ - @After - public void tearDown() throws Exception { - try { -// OLATResourceManager.getInstance().deleteOLATResource(course1); - DBFactory.getInstance().closeSession(); - } catch (Exception e) { - log.error("Exception in tearDown(): " + e); - e.printStackTrace(); - throw e; - } - } - - /** BGContextManagerImpl:createAndPersistBGContext * */ - @Test - public void testCreateAndPersistBGContext() { - BGContextManagerImpl bgcm = (BGContextManagerImpl)BGContextManagerImpl.getInstance(); - BGContext c1 = bgcm.createAndPersistBGContext("c1name", "c1desc", BusinessGroup.TYPE_LEARNINGROUP, null, true); - assertNotNull(c1); - BGContext c2 = bgcm.createAndPersistBGContext("c2name", "c2desc", BusinessGroup.TYPE_LEARNINGROUP, id1, false); - assertNotNull(c2); - try { - bgcm.createAndPersistBGContext("name", "desc", null, id2, false); - fail("context groupType can not be null"); - } catch (AssertException e) { - // expected exception - assertTrue(true); - } - try { - bgcm.createAndPersistBGContext(null, "desc", BusinessGroup.TYPE_LEARNINGROUP, id2, false); - fail("context name can not be null"); - } catch (AssertException e) { - // expected exception - assertTrue(true); - } - } - - /** BGContextManagerImpl:deleteBGContext() * */ - @Test - @Ignore - public void testDeleteBGContext() { - /*BGContextManagerImpl bgcm = (BGContextManagerImpl)BGContextManagerImpl.getInstance(); - BGContext c1 = bgcm.createAndPersistBGContext("c1name1", "c1desc1", BusinessGroup.TYPE_LEARNINGROUP, null, true); - BGContext c2 = bgcm.createAndPersistBGContext("c2name1", "c2desc1", BusinessGroup.TYPE_RIGHTGROUP, id1, false); - - DBFactory.getInstance().closeSession(); // simulate user clicks - BusinessGroupManager bgm = BusinessGroupManagerImpl.getInstance(); - - BusinessGroup g1 = bgm.createAndPersistBusinessGroup(BusinessGroup.TYPE_LEARNINGROUP, null, "g1", null, new Integer(0), - new Integer(10), false, false, c1); - BusinessGroup g2 = bgm.createAndPersistBusinessGroup(BusinessGroup.TYPE_LEARNINGROUP, null, "g2", null, new Integer(0), - new Integer(10), false, false, c1); - BusinessGroup g3 = bgm.createAndPersistBusinessGroup(BusinessGroup.TYPE_RIGHTGROUP, null, "g3", null, new Integer(0), - new Integer(10), false, false, c2); - - DBFactory.getInstance().closeSession(); // simulate user clicks - BaseSecurity secm = BaseSecurityManager.getInstance(); - secm.addIdentityToSecurityGroup(id1, g1.getPartipiciantGroup()); - secm.addIdentityToSecurityGroup(id1, g1.getOwnerGroup()); - secm.addIdentityToSecurityGroup(id2, g1.getPartipiciantGroup()); - secm.addIdentityToSecurityGroup(id3, g1.getOwnerGroup()); - secm.addIdentityToSecurityGroup(id4, g2.getPartipiciantGroup()); - secm.addIdentityToSecurityGroup(id4, g1.getOwnerGroup()); - secm.addIdentityToSecurityGroup(id1, g3.getPartipiciantGroup()); - secm.addIdentityToSecurityGroup(id2, g3.getPartipiciantGroup()); - - BGRightManagerImpl rm = BGRightManagerImpl.getInstance(); - rm.addBGRight(CourseRights.RIGHT_ARCHIVING, g3); - rm.addBGRight(CourseRights.RIGHT_COURSEEDITOR, g3); - DBFactory.getInstance().closeSession(); // simulate user clicks - - assertTrue(rm.hasBGRight(CourseRights.RIGHT_ARCHIVING, id1, c2)); - assertFalse(rm.hasBGRight(CourseRights.RIGHT_GROUPMANAGEMENT, id1, c2)); - assertTrue(rm.hasBGRight(CourseRights.RIGHT_ARCHIVING, id2, c2)); - assertFalse(rm.hasBGRight(CourseRights.RIGHT_ARCHIVING, id3, c2)); - - DBFactory.getInstance().closeSession(); // simulate user clicks - BGAreaManager am = BGAreaManagerImpl.getInstance(); - BGArea a1 = am.createAndPersistBGAreaIfNotExists("a1-delete", "desca1", c1); - BGArea a2 = am.createAndPersistBGAreaIfNotExists("a2-delete", null, c1); - BGArea a3 = am.createAndPersistBGAreaIfNotExists("a3-delete", "desca3", c1); - BGArea a4 = am.createAndPersistBGAreaIfNotExists("a4-delete", "desca4", c1); - am.addBGToBGArea(g1, a1); - am.addBGToBGArea(g2, a1); - am.addBGToBGArea(g1, a2); - am.addBGToBGArea(g2, a3); - am.addBGToBGArea(g1, a4); - DBFactory.getInstance().closeSession(); // simulate user clicks - - // test isIdentityInBGArea - assertTrue(am.isIdentityInBGArea(id1, "a1-delete", c1)); - assertTrue(am.isIdentityInBGArea(id1, "a2-delete", c1)); - assertFalse(am.isIdentityInBGArea(id1, "a3-delete", c1)); // not in group g2 - assertTrue(am.isIdentityInBGArea(id1, "a4-delete", c1)); - assertFalse(am.isIdentityInBGArea(id1, "xx", c1)); // wrong area name - assertFalse(am.isIdentityInBGArea(id1, "a1-delete", c2)); // wrong context - assertTrue(am.isIdentityInBGArea(id2, "a1-delete", c1)); - assertTrue(am.isIdentityInBGArea(id2, "a2-delete", c1)); - assertFalse(am.isIdentityInBGArea(id2, "a3-delete", c1)); // not in group g2 - assertTrue(am.isIdentityInBGArea(id2, "a4-delete", c1)); - assertTrue(am.isIdentityInBGArea(id3, "a1-delete", c1)); - assertTrue(am.isIdentityInBGArea(id3, "a2-delete", c1)); - assertFalse(am.isIdentityInBGArea(id3, "a3-delete", c1)); // not in group g2 - assertTrue(am.isIdentityInBGArea(id3, "a4-delete", c1)); - assertTrue(am.isIdentityInBGArea(id4, "a1-delete", c1)); - assertTrue(am.isIdentityInBGArea(id4, "a2-delete", c1)); - assertTrue(am.isIdentityInBGArea(id4, "a3-delete", c1)); - assertTrue(am.isIdentityInBGArea(id4, "a4-delete", c1)); - - DBFactory.getInstance().closeSession(); // simulate user clicks - assertTrue(am.findBGAreasOfBusinessGroup(g1).size() == 3); - assertTrue(am.findBGAreasOfBusinessGroup(g2).size() == 2); - assertTrue(am.findBGAreasOfBusinessGroup(g3).size() == 0); - - DBFactory.getInstance().closeSession(); // simulate user clicks - assertTrue(am.findBGAreasOfBGContext(c1).size() == 4); - assertTrue(am.findBGAreasOfBGContext(c2).size() == 0); - - DBFactory.getInstance().closeSession(); // simulate user clicks - assertTrue(am.findBusinessGroupsOfArea(a1).size() == 2); - assertTrue(am.findBusinessGroupsOfArea(a2).size() == 1); - assertTrue(am.findBusinessGroupsOfArea(a3).size() == 1); - assertTrue(am.findBusinessGroupsOfArea(a4).size() == 1); - - DBFactory.getInstance().closeSession(); // simulate user clicks - assertTrue(am.countBGAreasOfBGContext(c1) == 4); - assertTrue(am.countBGAreasOfBGContext(c2) == 0); - - DBFactory.getInstance().closeSession(); // simulate user clicks - assertTrue(am.findBusinessGroupsOfAreaAttendedBy(id1, "a1-delete", c1).size() == 1); - assertTrue(am.findBusinessGroupsOfAreaAttendedBy(id1, "a2-delete", c1).size() == 1); - assertTrue(am.findBusinessGroupsOfAreaAttendedBy(id1, "a3-delete", c1).size() == 0); - assertTrue(am.findBusinessGroupsOfAreaAttendedBy(id1, "a4-delete", c1).size() == 1); - assertTrue(am.findBusinessGroupsOfAreaAttendedBy(id4, "a1-delete", c1).size() == 1); - assertTrue(am.findBusinessGroupsOfAreaAttendedBy(id4, "a2-delete", c1).size() == 0); - assertTrue(am.findBusinessGroupsOfAreaAttendedBy(id4, "a3-delete", c1).size() == 1); - assertTrue(am.findBusinessGroupsOfAreaAttendedBy(id4, "a4-delete", c1).size() == 0); - - bgcm.deleteBGContext(c1); - // assertNull(DB.getInstance().findObject(BGContextImpl.class, - // c1.getKey())); - - bgcm.deleteBGContext(c2); - // assertNull(DB.getInstance().findObject(BGContextImpl.class, - // c2.getKey())); - - assertTrue(am.findBGAreasOfBGContext(c1).size() == 0); - assertNull(am.findBGArea("a1-delete", c1)); - assertTrue(am.findBGAreasOfBusinessGroup(g1).size() == 0); - assertTrue(am.findBGAreasOfBGContext(c2).size() == 0); - assertNull(am.findBGArea("a2-delete", c1)); - assertTrue(am.findBusinessGroupsOfArea(a1).size() == 0); - assertTrue(am.findBusinessGroupsOfArea(a2).size() == 0); - assertFalse(rm.hasBGRight(CourseRights.RIGHT_ARCHIVING, id1, c2)); - assertFalse(rm.hasBGRight(CourseRights.RIGHT_GROUPMANAGEMENT, id1, c2)); - assertFalse(rm.hasBGRight(CourseRights.RIGHT_ARCHIVING, id2, c2)); - assertFalse(rm.hasBGRight(CourseRights.RIGHT_ARCHIVING, id3, c2));*/ - } - - /** BGContextManagerImpl:copyBGContext() * */ - @Test @Ignore - public void testCopyBGContext() { - /* - BGContextManagerImpl bgcm = (BGContextManagerImpl)BGContextManagerImpl.getInstance(); - BGContext c1 = bgcm.createAndPersistBGContext("c1name2", "c1desc2", BusinessGroup.TYPE_LEARNINGROUP, null, true); - BGContext c2 = bgcm.createAndPersistBGContext("c2name2", "c2desc2", BusinessGroup.TYPE_RIGHTGROUP, id1, false); - - DBFactory.getInstance().closeSession(); // simulate user clicks - BusinessGroupManager bgm = BusinessGroupManagerImpl.getInstance(); - BusinessGroup g1 = bgm.createAndPersistBusinessGroup(BusinessGroup.TYPE_LEARNINGROUP, null, "g1", null, new Integer(0), - new Integer(10), false, false, c1); - BusinessGroup g2 = bgm.createAndPersistBusinessGroup(BusinessGroup.TYPE_LEARNINGROUP, null, "g2", null, new Integer(0), - new Integer(10), false, false, c1); - BusinessGroup g3 = bgm.createAndPersistBusinessGroup(BusinessGroup.TYPE_RIGHTGROUP, null, "g3", null, new Integer(0), - new Integer(10), false, false, c2); - - DBFactory.getInstance().closeSession(); // simulate user clicks - BaseSecurity secm = BaseSecurityManager.getInstance(); - secm.addIdentityToSecurityGroup(id1, g1.getPartipiciantGroup()); - secm.addIdentityToSecurityGroup(id1, g1.getOwnerGroup()); - secm.addIdentityToSecurityGroup(id2, g1.getPartipiciantGroup()); - secm.addIdentityToSecurityGroup(id3, g1.getOwnerGroup()); - secm.addIdentityToSecurityGroup(id1, g3.getPartipiciantGroup()); - secm.addIdentityToSecurityGroup(id2, g3.getPartipiciantGroup()); - - DBFactory.getInstance().closeSession(); // simulate user clicks - BGRightManagerImpl rm = BGRightManagerImpl.getInstance(); - rm.addBGRight(CourseRights.RIGHT_ARCHIVING, g3); - rm.addBGRight(CourseRights.RIGHT_COURSEEDITOR, g3); - - DBFactory.getInstance().closeSession(); // simulate user clicks - BGAreaManager am = BGAreaManagerImpl.getInstance(); - BGArea a1 = am.createAndPersistBGAreaIfNotExists("a1-copy", "desca1", c1); - BGArea a2 = am.createAndPersistBGAreaIfNotExists("a2-copy", null, c1); - am.addBGToBGArea(g1, a1); - am.addBGToBGArea(g2, a1); - am.addBGToBGArea(g1, a2); - DBFactory.getInstance().closeSession(); // simulate user clicks - - BGContext c1copy = bgcm.copyAndAddBGContextToResource(c1.getName(), course1, c1); - DBFactory.getInstance().closeSession(); // simulate user clicks - try { - bgcm.copyAndAddBGContextToResource(c2.getName(), course1, c2); - fail("expecting exeption"); - } catch (AssertException e) { - // ok, passed - } - DBFactory.getInstance().closeSession(); // simulate user clicks - - assertTrue(am.findBGAreasOfBGContext(c1copy).size() == 2); - assertNotNull(am.findBGArea("a1-copy", c1)); - assertNotNull(am.findBGArea("a2-copy", c1)); - assertNotNull(bgcm.findGroupOfBGContext(g1.getName(), c1copy)); - assertNotNull(bgcm.findGroupOfBGContext(g2.getName(), c1copy)); - assertTrue(bgcm.getGroupsOfBGContext(c1copy).size() == 2); - bgcm.deleteBGContext(c1copy); - */ - } - - /** BGContextManagerImpl:deleteBGContext() * */ - @Test - public void testBGRights() { - BGContextManagerImpl bgcm = (BGContextManagerImpl)BGContextManagerImpl.getInstance(); - BGContext bgctx1 = bgcm.createAndPersistBGContext("c1name3", "c1desc3", BusinessGroup.TYPE_RIGHTGROUP, null, true); - BGContext bgctx2 = bgcm.createAndPersistBGContext("c2name3", "c2desc3", BusinessGroup.TYPE_RIGHTGROUP, id1, false); - - OLATResource c1 = OLATResourceManager.getInstance().createOLATResourceInstance(bgctx1); - OLATResource c2 = OLATResourceManager.getInstance().createOLATResourceInstance(bgctx2); - - BusinessGroup g1 = businessGroupService.createBusinessGroup(null, "g1", null, BusinessGroup.TYPE_RIGHTGROUP, -1, -1, false, false, c1); - BusinessGroup g2 = businessGroupService.createBusinessGroup(null, "g2", null, BusinessGroup.TYPE_RIGHTGROUP, -1, -1, false, false, c1); - BusinessGroup g3 = businessGroupService.createBusinessGroup(null, "g3", null, BusinessGroup.TYPE_RIGHTGROUP, -1, -1, false, false, c2); - - BaseSecurity secm = BaseSecurityManager.getInstance(); - secm.addIdentityToSecurityGroup(id1, g1.getPartipiciantGroup()); - secm.addIdentityToSecurityGroup(id2, g1.getPartipiciantGroup()); - secm.addIdentityToSecurityGroup(id1, g2.getPartipiciantGroup()); - secm.addIdentityToSecurityGroup(id3, g3.getPartipiciantGroup()); - - rightManager.addBGRight(CourseRights.RIGHT_ARCHIVING, g1); - rightManager.addBGRight(CourseRights.RIGHT_COURSEEDITOR, g1); - rightManager.addBGRight(CourseRights.RIGHT_ARCHIVING, g2); - rightManager.addBGRight(CourseRights.RIGHT_COURSEEDITOR, g3); - DBFactory.getInstance().closeSession(); // simulate user clicks - - // secm.createAndPersistPolicy(rightGroup.getPartipiciantGroup(), bgRight, - // rightGroup.getGroupContext()); - List<SecurityGroup> groups = secm.getGroupsWithPermissionOnOlatResourceable(CourseRights.RIGHT_ARCHIVING, c1); - assertTrue(groups.size() == 2); - - List<Identity> identities = secm.getIdentitiesWithPermissionOnOlatResourceable(CourseRights.RIGHT_ARCHIVING, c2); - assertTrue(identities.size() == 2); - - List<Policy> policies = secm.getPoliciesOfSecurityGroup(g1.getPartipiciantGroup()); - assertTrue(policies.size() == 3); // read, archiving, courseeditor - - DBFactory.getInstance().closeSession(); // simulate user clicks - assertFalse(rightManager.hasBGRight(CourseRights.RIGHT_ARCHIVING, id1, c2)); - assertTrue(rightManager.hasBGRight(CourseRights.RIGHT_ARCHIVING, id1, c1)); - assertTrue(rightManager.hasBGRight(CourseRights.RIGHT_ARCHIVING, id2, c1)); - assertFalse(rightManager.hasBGRight(CourseRights.RIGHT_GROUPMANAGEMENT, id2, c1)); - assertFalse(rightManager.hasBGRight(CourseRights.RIGHT_ARCHIVING, id3, c2)); - assertTrue(rightManager.hasBGRight(CourseRights.RIGHT_COURSEEDITOR, id3, c2)); - assertFalse(rightManager.hasBGRight(CourseRights.RIGHT_COURSEEDITOR, id3, c1)); - - /* - * assertTrue(rm.hasBGRight(CourseRights.RIGHT_ARCHIVING, g1)); - * assertTrue(rm.hasBGRight(CourseRights.RIGHT_COURSEEDITOR, g1)); - * assertTrue(rm.hasBGRight(CourseRights.RIGHT_ARCHIVING, g2)); - * assertFalse(rm.hasBGRight(CourseRights.RIGHT_GROUPMANAGEMENT, g1)); - */ - assertTrue(rightManager.findBGRights(g1).size() == 2); - assertTrue(rightManager.findBGRights(g2).size() == 1); - - DBFactory.getInstance().closeSession(); // simulate user clicks - rightManager.removeBGRight(CourseRights.RIGHT_ARCHIVING, g1); - rightManager.removeBGRight(CourseRights.RIGHT_COURSEEDITOR, g1); - rightManager.removeBGRight(CourseRights.RIGHT_ARCHIVING, g2); - rightManager.removeBGRight(CourseRights.RIGHT_COURSEEDITOR, g3); - - DBFactory.getInstance().closeSession(); // simulate user clicks - assertFalse(rightManager.hasBGRight(CourseRights.RIGHT_ARCHIVING, id1, c1)); - assertFalse(rightManager.hasBGRight(CourseRights.RIGHT_ARCHIVING, id2, c1)); - assertFalse(rightManager.hasBGRight(CourseRights.RIGHT_COURSEEDITOR, id3, c2)); - - assertTrue(rightManager.findBGRights(g1).size() == 0); - assertTrue(rightManager.findBGRights(g2).size() == 0); - } - - /** BGContextManagerImpl:getGroupsOfBGContext and countGroupsOfBGContext* */ - @Test - public void testGroupsOfBGContext() { - OLATResource c1 = JunitTestHelper.createRandomResource(); - OLATResource c2 = JunitTestHelper.createRandomResource(); - - DBFactory.getInstance().closeSession(); // simulate user clicks - assertTrue(businessGroupService.findBusinessGroups(null, null, false, false, c1, 0, -1).isEmpty()); - assertTrue(businessGroupService.countBusinessGroups(null, null, false, false, c1) == 0); - - DBFactory.getInstance().closeSession(); // simulate user clicks - BusinessGroup g1 = businessGroupService.createBusinessGroup(null, "g1", null, BusinessGroup.TYPE_LEARNINGROUP, new Integer(0), - new Integer(10), false, false, c1); - assertNotNull(g1); - BusinessGroup g2 = businessGroupService.createBusinessGroup(null, "g2", null, BusinessGroup.TYPE_LEARNINGROUP, new Integer(0), - new Integer(10), false, false, c1); - assertNotNull(g2); - BusinessGroup g3 = businessGroupService.createBusinessGroup(null, "g3", null, BusinessGroup.TYPE_LEARNINGROUP, new Integer(0), - new Integer(10), false, false, c2); - assertNotNull(g3); - - BusinessGroup g2douplicate = businessGroupService.createBusinessGroup(null, "g2", null, BusinessGroup.TYPE_LEARNINGROUP, new Integer(0), - new Integer(10), false, false, c1); - assertNull(g2douplicate); // name douplicate names allowed per group context - - BusinessGroup g4 = businessGroupService.createBusinessGroup(null, "g2", null, BusinessGroup.TYPE_LEARNINGROUP, new Integer(0), - new Integer(10), false, false, c2); - assertNotNull(g4); // name douplicate in other context allowed - - DBFactory.getInstance().closeSession(); // simulate user clicks - assertTrue(businessGroupService.findBusinessGroups(null, null, false, false, c1, 0, -1).size() == 2); - assertTrue(businessGroupService.countBusinessGroups(null, null, false, false, c1) == 2); - } -} \ No newline at end of file diff --git a/src/test/java/org/olat/group/learninggroupexport.xml b/src/test/java/org/olat/group/manager/learninggroupexport.xml similarity index 100% rename from src/test/java/org/olat/group/learninggroupexport.xml rename to src/test/java/org/olat/group/manager/learninggroupexport.xml diff --git a/src/test/java/org/olat/group/rightgroupexport.xml b/src/test/java/org/olat/group/manager/rightgroupexport.xml similarity index 100% rename from src/test/java/org/olat/group/rightgroupexport.xml rename to src/test/java/org/olat/group/manager/rightgroupexport.xml diff --git a/src/test/java/org/olat/group/BGAreaManagerTest.java b/src/test/java/org/olat/group/test/BGAreaManagerTest.java similarity index 93% rename from src/test/java/org/olat/group/BGAreaManagerTest.java rename to src/test/java/org/olat/group/test/BGAreaManagerTest.java index eaf87ab415155361f7cae61b4c1190328fed3a65..bb827ea30900caf2ed25baa93949626dd83d5b24 100644 --- a/src/test/java/org/olat/group/BGAreaManagerTest.java +++ b/src/test/java/org/olat/group/test/BGAreaManagerTest.java @@ -24,7 +24,7 @@ * <p> */ -package org.olat.group; +package org.olat.group.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -44,14 +44,12 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; import org.olat.core.commons.persistence.DBFactory; -import org.olat.core.id.OLATResourceable; import org.olat.core.logging.OLog; import org.olat.core.logging.Tracing; -import org.olat.core.util.resource.OresHelper; import org.olat.group.area.BGArea; import org.olat.group.area.BGAreaManager; import org.olat.resource.OLATResource; -import org.olat.resource.OLATResourceManager; +import org.olat.test.JunitTestHelper; import org.olat.test.OlatTestCase; import org.springframework.beans.factory.annotation.Autowired; @@ -68,20 +66,17 @@ public class BGAreaManagerTest extends OlatTestCase { @Autowired private BGAreaManager areaManager; - @Before public void setUp() { try { - OLATResourceable ores1 = OresHelper.createOLATResourceableInstance(UUID.randomUUID().toString(), 0l); - c1 = OLATResourceManager.getInstance().createOLATResourceInstance(ores1); - OLATResourceable ores2 = OresHelper.createOLATResourceableInstance(UUID.randomUUID().toString(), 0l); - c2 = OLATResourceManager.getInstance().createOLATResourceInstance(ores2); + c1 = JunitTestHelper.createRandomResource(); + Assert.assertNotNull(c1); + c2 = JunitTestHelper.createRandomResource(); Assert.assertNotNull(c2); DBFactory.getInstance().closeSession(); } catch (Exception e) { log.error("Exception in setUp(): " + e); - e.printStackTrace(); } } @@ -91,11 +86,17 @@ public class BGAreaManagerTest extends OlatTestCase { DBFactory.getInstance().closeSession(); } catch (Exception e) { log.error("Exception in tearDown(): " + e); - e.printStackTrace(); throw e; } } - + + @Test + public void testCreateBGArea() { + String areaName = UUID.randomUUID().toString(); + BGArea bgArea = areaManager.createAndPersistBGAreaIfNotExists(areaName, "description:" + areaName, c1); + Assert.assertNotNull(bgArea); + DBFactory.getInstance().commit(); + } /** * Do in different threads ant check that no exception happens : diff --git a/src/test/java/org/olat/group/test/BGRightManagerTest.java b/src/test/java/org/olat/group/test/BGRightManagerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..a143b5fb7e16910599be15554292162a1f902afe --- /dev/null +++ b/src/test/java/org/olat/group/test/BGRightManagerTest.java @@ -0,0 +1,170 @@ +/** +* OLAT - Online Learning and Training<br> +* http://www.olat.org +* <p> +* Licensed under the Apache License, Version 2.0 (the "License"); <br> +* you may not use this file except in compliance with the License.<br> +* You may obtain a copy of the License at +* <p> +* http://www.apache.org/licenses/LICENSE-2.0 +* <p> +* Unless required by applicable law or agreed to in writing,<br> +* software distributed under the License is distributed on an "AS IS" BASIS, <br> +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> +* See the License for the specific language governing permissions and <br> +* limitations under the License. +* <p> +* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> +* University of Zurich, Switzerland. +* <hr> +* <a href="http://www.openolat.org"> +* OpenOLAT - Online Learning and Training</a><br> +* This file has been modified by the OpenOLAT community. Changes are licensed +* under the Apache 2.0 license as the original file. +* <p> +*/ + +package org.olat.group.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import junit.framework.Assert; + +import org.apache.log4j.Logger; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.olat.basesecurity.BaseSecurity; +import org.olat.basesecurity.Policy; +import org.olat.basesecurity.SecurityGroup; +import org.olat.core.commons.persistence.DBFactory; +import org.olat.core.id.Identity; +import org.olat.course.groupsandrights.CourseRights; +import org.olat.group.BusinessGroup; +import org.olat.group.BusinessGroupService; +import org.olat.group.right.BGRightManager; +import org.olat.resource.OLATResource; +import org.olat.test.JunitTestHelper; +import org.olat.test.OlatTestCase; +import org.springframework.beans.factory.annotation.Autowired; + +/** + * Description:<BR> + * Initial Date: Aug 18, 2004 + * + * @author gnaegi + */ +public class BGRightManagerTest extends OlatTestCase { + + private static Logger log = Logger.getLogger(BGRightManagerTest.class.getName()); + private Identity id1, id2, id3, id4; + + @Autowired + private BusinessGroupService businessGroupService; + @Autowired + private BGRightManager rightManager; + @Autowired + private BaseSecurity securityManager; + + /** + * SetUp is called before each test. + */ + @Before + public void setUp() { + try { + id1 = JunitTestHelper.createAndPersistIdentityAsUser("one"); + id2 = JunitTestHelper.createAndPersistIdentityAsUser("twoo"); + id3 = JunitTestHelper.createAndPersistIdentityAsUser("three"); + id4 = JunitTestHelper.createAndPersistIdentityAsUser("four"); + Assert.assertNotNull(id1); + Assert.assertNotNull(id2); + Assert.assertNotNull(id3); + Assert.assertNotNull(id4); + } catch (Exception e) { + log.error("Exception in setUp(): " + e); + } + } + + /** + * TearDown is called after each test. + * + * @throws Exception + */ + @After + public void tearDown() throws Exception { + try { + DBFactory.getInstance().closeSession(); + } catch (Exception e) { + log.error("Exception in tearDown(): " + e); + throw e; + } + } + + /** BGContextManagerImpl:deleteBGContext() * */ + @Test + public void testBGRights() { + OLATResource c1 = JunitTestHelper.createRandomResource(); + OLATResource c2 = JunitTestHelper.createRandomResource(); + + BusinessGroup g1 = businessGroupService.createBusinessGroup(null, "g1", null, BusinessGroup.TYPE_RIGHTGROUP, -1, -1, false, false, c1); + BusinessGroup g2 = businessGroupService.createBusinessGroup(null, "g2", null, BusinessGroup.TYPE_RIGHTGROUP, -1, -1, false, false, c1); + BusinessGroup g3 = businessGroupService.createBusinessGroup(null, "g3", null, BusinessGroup.TYPE_RIGHTGROUP, -1, -1, false, false, c2); + + securityManager.addIdentityToSecurityGroup(id1, g1.getPartipiciantGroup()); + securityManager.addIdentityToSecurityGroup(id2, g1.getPartipiciantGroup()); + securityManager.addIdentityToSecurityGroup(id1, g2.getPartipiciantGroup()); + securityManager.addIdentityToSecurityGroup(id3, g3.getPartipiciantGroup()); + + rightManager.addBGRight(CourseRights.RIGHT_ARCHIVING, g1); + rightManager.addBGRight(CourseRights.RIGHT_COURSEEDITOR, g1); + rightManager.addBGRight(CourseRights.RIGHT_ARCHIVING, g2); + rightManager.addBGRight(CourseRights.RIGHT_COURSEEDITOR, g3); + DBFactory.getInstance().closeSession(); // simulate user clicks + + // secm.createAndPersistPolicy(rightGroup.getPartipiciantGroup(), bgRight, + // rightGroup.getGroupContext()); + List<SecurityGroup> groups = securityManager.getGroupsWithPermissionOnOlatResourceable(CourseRights.RIGHT_ARCHIVING, c1); + Assert.assertEquals(2, groups.size()); + + List<Identity> identities = securityManager.getIdentitiesWithPermissionOnOlatResourceable(CourseRights.RIGHT_ARCHIVING, c1); + Assert.assertEquals(2, identities.size()); + + List<Policy> policies = securityManager.getPoliciesOfSecurityGroup(g1.getPartipiciantGroup()); + Assert.assertEquals(3, policies.size()); // read, archiving, courseeditor + + DBFactory.getInstance().closeSession(); // simulate user clicks + assertFalse(rightManager.hasBGRight(CourseRights.RIGHT_ARCHIVING, id1, c2)); + assertTrue(rightManager.hasBGRight(CourseRights.RIGHT_ARCHIVING, id1, c1)); + assertTrue(rightManager.hasBGRight(CourseRights.RIGHT_ARCHIVING, id2, c1)); + assertFalse(rightManager.hasBGRight(CourseRights.RIGHT_GROUPMANAGEMENT, id2, c1)); + assertFalse(rightManager.hasBGRight(CourseRights.RIGHT_ARCHIVING, id3, c2)); + assertTrue(rightManager.hasBGRight(CourseRights.RIGHT_COURSEEDITOR, id3, c2)); + assertFalse(rightManager.hasBGRight(CourseRights.RIGHT_COURSEEDITOR, id3, c1)); + + /* + * assertTrue(rm.hasBGRight(CourseRights.RIGHT_ARCHIVING, g1)); + * assertTrue(rm.hasBGRight(CourseRights.RIGHT_COURSEEDITOR, g1)); + * assertTrue(rm.hasBGRight(CourseRights.RIGHT_ARCHIVING, g2)); + * assertFalse(rm.hasBGRight(CourseRights.RIGHT_GROUPMANAGEMENT, g1)); + */ + Assert.assertEquals(2, rightManager.findBGRights(g1).size()); + Assert.assertEquals(1, rightManager.findBGRights(g2).size()); + + DBFactory.getInstance().closeSession(); // simulate user clicks + rightManager.removeBGRight(CourseRights.RIGHT_ARCHIVING, g1); + rightManager.removeBGRight(CourseRights.RIGHT_COURSEEDITOR, g1); + rightManager.removeBGRight(CourseRights.RIGHT_ARCHIVING, g2); + rightManager.removeBGRight(CourseRights.RIGHT_COURSEEDITOR, g3); + + DBFactory.getInstance().closeSession(); // simulate user clicks + assertFalse(rightManager.hasBGRight(CourseRights.RIGHT_ARCHIVING, id1, c1)); + assertFalse(rightManager.hasBGRight(CourseRights.RIGHT_ARCHIVING, id2, c1)); + assertFalse(rightManager.hasBGRight(CourseRights.RIGHT_COURSEEDITOR, id3, c2)); + + Assert.assertEquals(0, rightManager.findBGRights(g1).size()); + Assert.assertEquals(0, rightManager.findBGRights(g2).size()); + } +} \ No newline at end of file diff --git a/src/test/java/org/olat/group/BusinessGroupManagerImplTest.java b/src/test/java/org/olat/group/test/BusinessGroupServiceImplTest.java similarity index 94% rename from src/test/java/org/olat/group/BusinessGroupManagerImplTest.java rename to src/test/java/org/olat/group/test/BusinessGroupServiceImplTest.java index 5f6d1075011ebc2cfe284d46cd7053f92dc05133..2a09de602cbbcdf4c92b9dd48df4783773d7e2e4 100644 --- a/src/test/java/org/olat/group/BusinessGroupManagerImplTest.java +++ b/src/test/java/org/olat/group/test/BusinessGroupServiceImplTest.java @@ -24,7 +24,7 @@ * <p> */ -package org.olat.group; +package org.olat.group.test; // um click emulieren: /* @@ -43,6 +43,7 @@ import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.UUID; import org.apache.log4j.Logger; import org.junit.After; @@ -64,6 +65,8 @@ import org.olat.core.id.Identity; import org.olat.core.id.User; import org.olat.core.id.context.BusinessControl; import org.olat.core.util.Encoder; +import org.olat.group.BusinessGroup; +import org.olat.group.BusinessGroupService; import org.olat.group.ui.BGConfigFlags; import org.olat.resource.OLATResource; import org.olat.test.JunitTestHelper; @@ -78,9 +81,9 @@ import org.springframework.beans.factory.annotation.Autowired; * @author patrick */ -public class BusinessGroupManagerImplTest extends OlatTestCase implements WindowControl { +public class BusinessGroupServiceImplTest extends OlatTestCase implements WindowControl { // - private static Logger log = Logger.getLogger(BusinessGroupManagerImplTest.class.getName()); + private static Logger log = Logger.getLogger(BusinessGroupServiceImplTest.class.getName()); /* * ::Test Setup:: */ @@ -126,12 +129,15 @@ public class BusinessGroupManagerImplTest extends OlatTestCase implements Window @Autowired private BusinessGroupService businessGroupService; + private static boolean initialize = false; /** * @see junit.framework.TestCase#setUp() */ @Before public void setUp() throws Exception { + if(initialize) return; + // Identities id1 = JunitTestHelper.createAndPersistIdentityAsUser("id1"); id2 = JunitTestHelper.createAndPersistIdentityAsUser("id2"); @@ -177,10 +183,37 @@ public class BusinessGroupManagerImplTest extends OlatTestCase implements Window DBFactory.getInstance().closeSession(); - setupWaitingList(businessGroupService); - /* - * phuuu finally initialized - */ + // create business-group with waiting-list + String bgWithWaitingListName = "Group with WaitingList"; + String bgWithWaitingListDesc = "some short description for Group with WaitingList"; + Boolean enableWaitinglist = new Boolean(true); + Boolean enableAutoCloseRanks = new Boolean(true); + OLATResource resource = JunitTestHelper.createRandomResource(); + System.out.println("testAddToWaitingListAndFireEvent: resource=" + resource); + bgWithWaitingList = businessGroupService.createBusinessGroup(id1, bgWithWaitingListName, + bgWithWaitingListDesc, BusinessGroup.TYPE_LEARNINGROUP, -1, -1, enableWaitinglist, enableAutoCloseRanks, resource); + bgWithWaitingList.setMaxParticipants(new Integer(2)); + // Identities + String suffix = UUID.randomUUID().toString(); + User UserWg1 = UserManager.getInstance().createAndPersistUser("FirstName_" + suffix, "LastName_" + suffix, suffix + "_junittest@olat.unizh.ch"); + wg1 = BaseSecurityManager.getInstance().createAndPersistIdentity(suffix, UserWg1, + BaseSecurityModule.getDefaultAuthProviderIdentifier(), suffix, Encoder.encrypt("wg1")); + suffix = UUID.randomUUID().toString(); + User UserWg2 = UserManager.getInstance().createAndPersistUser("FirstName_" + suffix, "LastName_" + suffix, suffix + "_junittest@olat.unizh.ch"); + wg2 = BaseSecurityManager.getInstance().createAndPersistIdentity(suffix, UserWg2, + BaseSecurityModule.getDefaultAuthProviderIdentifier(), suffix, Encoder.encrypt("wg2")); + suffix = UUID.randomUUID().toString(); + User UserWg3 = UserManager.getInstance().createAndPersistUser("FirstName_" + suffix, "LastName_" + suffix, suffix + "_junittest@olat.unizh.ch"); + wg3 = BaseSecurityManager.getInstance().createAndPersistIdentity(suffix, UserWg3, + BaseSecurityModule.getDefaultAuthProviderIdentifier(), suffix, Encoder.encrypt("wg3")); + suffix = UUID.randomUUID().toString(); + User UserWg4 = UserManager.getInstance().createAndPersistUser("FirstName_" + suffix, "LastName_" + suffix, suffix + "_junittest@olat.unizh.ch"); + wg4 = BaseSecurityManager.getInstance().createAndPersistIdentity(suffix, UserWg4, + BaseSecurityModule.getDefaultAuthProviderIdentifier(), suffix, Encoder.encrypt("wg4")); + + DBFactory.getInstance().closeSession(); + + initialize = true; } @Test @@ -594,36 +627,7 @@ public class BusinessGroupManagerImplTest extends OlatTestCase implements Window } } - // Helper methods - // /////////////// - private void setupWaitingList(BusinessGroupService bgManager) { - if (bgManager.findBusinessGroupsOwnedBy(BusinessGroup.TYPE_LEARNINGROUP, id1, null).size() == 0) { - // create business-group with waiting-list - String bgWithWaitingListName = "Group with WaitingList"; - String bgWithWaitingListDesc = "some short description for Group with WaitingList"; - Boolean enableWaitinglist = new Boolean(true); - Boolean enableAutoCloseRanks = new Boolean(true); - OLATResource resource = JunitTestHelper.createRandomResource(); - System.out.println("testAddToWaitingListAndFireEvent: resource=" + resource); - bgWithWaitingList = businessGroupService.createBusinessGroup(id1, bgWithWaitingListName, - bgWithWaitingListDesc, BusinessGroup.TYPE_LEARNINGROUP, -1, -1, enableWaitinglist, enableAutoCloseRanks, resource); - bgWithWaitingList.setMaxParticipants(new Integer(2)); - // Identities - User UserWg1 = UserManager.getInstance().createAndPersistUser("FirstName_wg1", "LastName_wg1", "wg1_junittest@olat.unizh.ch"); - wg1 = BaseSecurityManager.getInstance().createAndPersistIdentity("wg1", UserWg1, - BaseSecurityModule.getDefaultAuthProviderIdentifier(), "wg1", Encoder.encrypt("wg1")); - User UserWg2 = UserManager.getInstance().createAndPersistUser("FirstName_wg2", "LastName_wg2", "wg2_junittest@olat.unizh.ch"); - wg2 = BaseSecurityManager.getInstance().createAndPersistIdentity("wg2", UserWg2, - BaseSecurityModule.getDefaultAuthProviderIdentifier(), "wg2", Encoder.encrypt("wg2")); - User UserWg3 = UserManager.getInstance().createAndPersistUser("FirstName_wg3", "LastName_wg3", "wg3_junittest@olat.unizh.ch"); - wg3 = BaseSecurityManager.getInstance().createAndPersistIdentity("wg3", UserWg3, - BaseSecurityModule.getDefaultAuthProviderIdentifier(), "wg3", Encoder.encrypt("wg3")); - User UserWg4 = UserManager.getInstance().createAndPersistUser("FirstName_wg4", "LastName_wg4", "wg4_junittest@olat.unizh.ch"); - wg4 = BaseSecurityManager.getInstance().createAndPersistIdentity("wg4", UserWg4, - BaseSecurityModule.getDefaultAuthProviderIdentifier(), "wg4", Encoder.encrypt("wg4")); - } - } // Implements interface WindowControl // /////////////////////////////////// diff --git a/src/test/java/org/olat/group/test/BusinessGroupServiceTest.java b/src/test/java/org/olat/group/test/BusinessGroupServiceTest.java index ad6b6a88d9d5ea75849ffc978b9b2a59a0dd6514..f299392adad13efcb8519ed0679826df9b9f81cc 100644 --- a/src/test/java/org/olat/group/test/BusinessGroupServiceTest.java +++ b/src/test/java/org/olat/group/test/BusinessGroupServiceTest.java @@ -1,7 +1,10 @@ package org.olat.group.test; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + import java.util.List; -import java.util.UUID; import junit.framework.Assert; @@ -9,14 +12,13 @@ import org.junit.After; import org.junit.Test; import org.olat.core.commons.persistence.DB; import org.olat.core.commons.persistence.DBFactory; -import org.olat.core.id.OLATResourceable; import org.olat.core.logging.OLog; import org.olat.core.logging.Tracing; import org.olat.group.BusinessGroup; import org.olat.group.BusinessGroupService; import org.olat.group.model.SearchBusinessGroupParams; import org.olat.resource.OLATResource; -import org.olat.resource.OLATResourceManager; +import org.olat.test.JunitTestHelper; import org.olat.test.OlatTestCase; import org.springframework.beans.factory.annotation.Autowired; @@ -31,9 +33,7 @@ public class BusinessGroupServiceTest extends OlatTestCase { @Autowired private DB dbInstance; @Autowired - private BusinessGroupService groupService; - @Autowired - private OLATResourceManager olatResourceManager; + private BusinessGroupService businessGroupService; @After public void tearDown() throws Exception { @@ -47,50 +47,61 @@ public class BusinessGroupServiceTest extends OlatTestCase { @Test public void should_service_present() { - Assert.assertNotNull(groupService); - Assert.assertNotNull(olatResourceManager); + Assert.assertNotNull(businessGroupService); } @Test public void createBusinessGroup() { - BusinessGroup group = groupService.createBusinessGroup(null, "gdao", "gdao-desc", BusinessGroup.TYPE_LEARNINGROUP, -1, -1, false, false, null); + BusinessGroup group = businessGroupService.createBusinessGroup(null, "gdao", "gdao-desc", BusinessGroup.TYPE_LEARNINGROUP, -1, -1, false, false, null); Assert.assertNotNull(group); } @Test public void createBusinessGroupWithResource() { - String resourceType = UUID.randomUUID().toString(); - OLATResource resource = olatResourceManager.createOLATResourceInstance(new TestResource(resourceType)); - olatResourceManager.saveOLATResource(resource); - BusinessGroup group = groupService.createBusinessGroup(null, "gdao", "gdao-desc", BusinessGroup.TYPE_LEARNINGROUP, -1, -1, false, false, resource); + OLATResource resource = JunitTestHelper.createRandomResource(); + BusinessGroup group = businessGroupService.createBusinessGroup(null, "gdao", "gdao-desc", BusinessGroup.TYPE_LEARNINGROUP, -1, -1, false, false, resource); //commit the group dbInstance.commit(); Assert.assertNotNull(group); } + @Test public void loadBusinessGroups() { SearchBusinessGroupParams params = new SearchBusinessGroupParams(); - List<BusinessGroup> groups = groupService.findBusinessGroups(params, null, false, false, null, 0, 5); + List<BusinessGroup> groups = businessGroupService.findBusinessGroups(params, null, false, false, null, 0, 5); Assert.assertNotNull(groups); } - private static class TestResource implements OLATResourceable { - private String type; - - public TestResource(String type) { - this.type = type; - } + @Test + public void testGroupsOfBGContext() { + OLATResource c1 = JunitTestHelper.createRandomResource(); + OLATResource c2 = JunitTestHelper.createRandomResource(); - @Override - public String getResourceableTypeName() { - return type; - } + DBFactory.getInstance().closeSession(); // simulate user clicks + assertTrue(businessGroupService.findBusinessGroups(null, null, false, false, c1, 0, -1).isEmpty()); + assertTrue(businessGroupService.countBusinessGroups(null, null, false, false, c1) == 0); - @Override - public Long getResourceableId() { - return 1l; - } + DBFactory.getInstance().closeSession(); // simulate user clicks + BusinessGroup g1 = businessGroupService.createBusinessGroup(null, "g1", null, BusinessGroup.TYPE_LEARNINGROUP, 0, 10, false, false, c1); + assertNotNull(g1); + BusinessGroup g2 = businessGroupService.createBusinessGroup(null, "g2", null, BusinessGroup.TYPE_LEARNINGROUP, 0, 10, false, false, c1); + assertNotNull(g2); + BusinessGroup g3 = businessGroupService.createBusinessGroup(null, "g3", null, BusinessGroup.TYPE_LEARNINGROUP, 0, 10, false, false, c2); + assertNotNull(g3); + + BusinessGroup g2douplicate = businessGroupService.createBusinessGroup(null, "g2", null, BusinessGroup.TYPE_LEARNINGROUP, 0, 10, false, false, c1); + assertNull(g2douplicate); // name duplicate names allowed per group context + + BusinessGroup g4 = businessGroupService.createBusinessGroup(null, "g2", null, BusinessGroup.TYPE_LEARNINGROUP, 0, 10, false, false, c2); + assertNotNull(g4); // name duplicate in other context allowed + + DBFactory.getInstance().closeSession(); // simulate user clicks + Assert.assertEquals(2, businessGroupService.findBusinessGroups(null, null, false, false, c1, 0, -1).size()); + Assert.assertEquals(2, businessGroupService.countBusinessGroups(null, null, false, false, c1)); } + + + } diff --git a/src/test/java/org/olat/instantMessaging/IMPrefsUnitTest.java b/src/test/java/org/olat/instantMessaging/IMPrefsUnitTest.java index 529f0afaca75597558e395a4d2ff40200e1adaf6..08b344abf9e525176368ad56759ba691a81988a2 100644 --- a/src/test/java/org/olat/instantMessaging/IMPrefsUnitTest.java +++ b/src/test/java/org/olat/instantMessaging/IMPrefsUnitTest.java @@ -30,14 +30,12 @@ import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.UUID; import org.junit.After; import org.junit.Before; import org.junit.Test; -import junit.framework.TestSuite; - -import org.olat.basesecurity.BaseSecurityManager; -import org.olat.core.commons.persistence.DB; +import org.olat.basesecurity.BaseSecurity; import org.olat.core.commons.persistence.DBFactory; import org.olat.core.commons.taskExecutor.TaskExecutorManager; import org.olat.core.id.Identity; @@ -45,6 +43,7 @@ import org.olat.core.logging.OLog; import org.olat.core.logging.Tracing; import org.olat.test.JunitTestHelper; import org.olat.test.OlatTestCase; +import org.springframework.beans.factory.annotation.Autowired; /** * Description:<br> @@ -54,30 +53,30 @@ import org.olat.test.OlatTestCase; * Initial Date: 12.08.2008 <br> * @author guido */ - public class IMPrefsUnitTest extends OlatTestCase { - OLog log = Tracing.createLoggerFor(this.getClass()); - String testUserA = "anIdentity1"; - String testUserB = "anIdentity2"; - String testUserC = "anIdentity3"; - String testUserD = "anIdentity4"; - +public class IMPrefsUnitTest extends OlatTestCase { + private OLog log = Tracing.createLoggerFor(IMPrefsUnitTest.class); + private String testUserA = "anIdentity1-" + UUID.randomUUID().toString(); + private String testUserB = "anIdentity2-" + UUID.randomUUID().toString(); + private String testUserC = "anIdentity3-" + UUID.randomUUID().toString(); + private String testUserD = "anIdentity4-" + UUID.randomUUID().toString(); - - @SuppressWarnings("unchecked") - @Test public void testPrefs() { - List usernames = new ArrayList(); - List indentities = new ArrayList(); + @Autowired + private BaseSecurity securityManager; + + @Test + public void testPrefs() { + List<String> usernames = new ArrayList<String>(); + List<Identity> identities = new ArrayList<Identity>(); usernames.add(testUserA); usernames.add(testUserB); usernames.add(testUserC); usernames.add(testUserD); - - for (Iterator iterator = usernames.iterator(); iterator.hasNext();) { - String name = (String) iterator.next(); - Identity ident = BaseSecurityManager.getInstance().findIdentityByName(name); + for (Iterator<String> iterator = usernames.iterator(); iterator.hasNext();) { + String name = iterator.next(); + Identity ident = securityManager.findIdentityByName(name); assertNotNull(ident); - indentities.add(ident); + identities.add(ident); } long start = System.currentTimeMillis(); @@ -86,25 +85,23 @@ import org.olat.test.OlatTestCase; double rand = Math.random()*3; int i = Long.valueOf((Math.round(rand))).intValue(); ImPrefsManager mgr = ImPrefsManager.getInstance(); - Identity ident = (Identity)indentities.get(i); - ImPreferences prefs = mgr.loadOrCreatePropertiesFor((Identity)indentities.get(i)); + Identity ident = identities.get(i); + ImPreferences prefs = mgr.loadOrCreatePropertiesFor(ident); assertNotNull(prefs); assertNotNull(prefs.getDbProperty()); try { Thread.sleep(100); } catch (InterruptedException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); + log.error("", e1); } - for (Iterator iterator = indentities.iterator(); iterator.hasNext();) { - ident = (Identity) iterator.next(); + for (Iterator<Identity> iterator = identities.iterator(); iterator.hasNext();) { + ident = iterator.next(); TaskExecutorManager.getInstance().runTask(new IMPrefsTask(ident)); try { Thread.sleep(20); } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + log.error("", e); } } runs++; @@ -117,7 +114,8 @@ import org.olat.test.OlatTestCase; /** * @see junit.framework.TestCase#setUp() */ - @Before public void setup()throws Exception { + @Before + public void setup()throws Exception { JunitTestHelper.createAndPersistIdentityAsUser(testUserA); JunitTestHelper.createAndPersistIdentityAsUser(testUserB); JunitTestHelper.createAndPersistIdentityAsUser(testUserC); @@ -130,11 +128,9 @@ import org.olat.test.OlatTestCase; */ @After public void tearDown() { try { - DB db = DBFactory.getInstance(); - db.closeSession(); + DBFactory.getInstance().closeSession(); } catch (Exception e) { - Tracing.logError("Exception in tearDown(): " + e, IMUnitTest.class); + log.error("Exception in tearDown(): " + e); } } - } diff --git a/src/test/java/org/olat/notifications/NotificationsManagerTest.java b/src/test/java/org/olat/notifications/NotificationsManagerTest.java index 6521b5ee8b6b909693e248d8ed722f4b03c632c9..8dea1f333c02f80217385df21c92b20d4f0a5caf 100644 --- a/src/test/java/org/olat/notifications/NotificationsManagerTest.java +++ b/src/test/java/org/olat/notifications/NotificationsManagerTest.java @@ -38,12 +38,14 @@ import java.util.Collections; import java.util.List; import java.util.UUID; -import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.olat.core.commons.persistence.DB; import org.olat.core.commons.persistence.DBFactory; import org.olat.core.id.Identity; +import org.olat.core.logging.OLog; +import org.olat.core.logging.Tracing; import org.olat.core.util.notifications.NotificationsManager; import org.olat.core.util.notifications.Publisher; import org.olat.core.util.notifications.PublisherData; @@ -57,6 +59,7 @@ import org.olat.testutils.codepoints.client.CodepointClientFactory; import org.olat.testutils.codepoints.client.CodepointRef; import org.olat.testutils.codepoints.client.CommunicationException; import org.olat.testutils.codepoints.client.TemporaryPausedThread; +import org.springframework.beans.factory.annotation.Autowired; /** * Initial Date: Dec 9, 2004 @@ -68,22 +71,29 @@ import org.olat.testutils.codepoints.client.TemporaryPausedThread; */ public class NotificationsManagerTest extends OlatTestCase { - private static Logger log = Logger.getLogger(NotificationsManagerTest.class); + private static OLog log = Tracing.createLoggerFor(NotificationsManagerTest.class); private static final String CODEPOINT_SERVER_ID = "NotificationsManagerTest"; - private static Identity identity, identity2, identity3; - private static NotificationsManager nm; + private static Identity identity1, identity2, identity3; + + @Autowired + private NotificationsManager notificationManager; + @Autowired + private DB dbInstance; + + /** * @see junit.framework.TestCase#setUp() */ - @Before public void setup() { - nm = NotificationsManager.getInstance(); + @Before + public void setup() { // identity with null User should be ok for test case - identity = JunitTestHelper.createAndPersistIdentityAsUser("fi1"); - identity2 = JunitTestHelper.createAndPersistIdentityAsUser("fi2"); - identity3 = JunitTestHelper.createAndPersistIdentityAsUser("fi3"); + identity1 = JunitTestHelper.createAndPersistIdentityAsUser("fi1-" + UUID.randomUUID().toString()); + identity2 = JunitTestHelper.createAndPersistIdentityAsUser("fi2-" + UUID.randomUUID().toString()); + identity3 = JunitTestHelper.createAndPersistIdentityAsUser("fi3-" + UUID.randomUUID().toString()); + dbInstance.commit(); } /** @@ -97,11 +107,8 @@ public class NotificationsManagerTest extends OlatTestCase { } } - /** - * - * - */ - @Test public void testSubscriptions() { + @Test + public void testSubscriptions() { SubscriptionContext sc = new SubscriptionContext("Course", new Long(123), "676"); PublisherData pd = new PublisherData("Forum", "e.g. forumdata=keyofforum", null); @@ -112,37 +119,35 @@ public class NotificationsManagerTest extends OlatTestCase { //assertNull(p); DBFactory.getInstance().closeSession(); - nm.subscribe(identity, sc, pd); - nm.subscribe(identity3, sc, pd); - nm.subscribe(identity2, sc2, pd2); - nm.subscribe(identity, sc2, pd2); + notificationManager.subscribe(identity1, sc, pd); + notificationManager.subscribe(identity3, sc, pd); + notificationManager.subscribe(identity2, sc2, pd2); + notificationManager.subscribe(identity1, sc2, pd2); DBFactory.getInstance().closeSession(); - Publisher p = nm.getPublisher(sc); + Publisher p = notificationManager.getPublisher(sc); assertNotNull(p); assertEquals(p.getResName(), sc.getResName()); assertEquals(p.getResId(), sc.getResId()); assertEquals(p.getSubidentifier(), sc.getSubidentifier()); - boolean isSub = nm.isSubscribed(identity, sc); + boolean isSub = notificationManager.isSubscribed(identity1, sc); assertTrue("subscribed::", isSub); - //List subs = nm.getValidSubscribers(identity); - - nm.notifyAllSubscribersByEmail(); + notificationManager.notifyAllSubscribersByEmail(); DBFactory.getInstance().closeSession(); - nm.unsubscribe(identity, sc); + notificationManager.unsubscribe(identity1, sc); DBFactory.getInstance().closeSession(); - boolean isStillSub = nm.isSubscribed(identity, sc); + boolean isStillSub = notificationManager.isSubscribed(identity1, sc); assertFalse("subscribed::", isStillSub); - nm.delete(sc); + notificationManager.delete(sc); - Publisher p2 = nm.getPublisher(sc); + Publisher p2 = notificationManager.getPublisher(sc); assertNull("publisher marked deleted should not be found", p2); } @@ -151,7 +156,8 @@ public class NotificationsManagerTest extends OlatTestCase { * Start 2 threads which call 'subscribe' with same SubscriptionContext. * Breakpoint at doInSync, second thread must wait until thread 1 has released the breakpoint. */ - @Test public void testConcurrentFindOrCreatePublisher() { + @Test + public void testConcurrentFindOrCreatePublisher() { JMSCodePointServerJunitHelper.startServer(CODEPOINT_SERVER_ID); @@ -170,8 +176,7 @@ public class NotificationsManagerTest extends OlatTestCase { codepointRef = codepointClient.getCodepoint("org.olat.commons.coordinate.cluster.ClusterSyncer.doInSync-in-sync.org.olat.notifications.NotificationsManagerImpl.findOrCreatePublisher"); codepointRef.enableBreakpoint(); } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); + log.error("", e); fail("Could not initialize CodepointClient"); } @@ -179,7 +184,7 @@ public class NotificationsManagerTest extends OlatTestCase { new Thread(new Runnable() { public void run() { try { - NotificationsManager.getInstance().subscribe(identity, sc, pd); + NotificationsManager.getInstance().subscribe(identity1, sc, pd); DBFactory.getInstance().closeSession(); statusList.add(Boolean.TRUE); System.out.println("testConcurrentFindOrCreatePublisher thread1 finished"); @@ -227,27 +232,24 @@ public class NotificationsManagerTest extends OlatTestCase { // sleep until t1 and t2 should have terminated/excepted int loopCount = 0; - while ( (statusList.size()<2) && (exceptionHolder.size()<1) && (loopCount<5)) { + while ( (statusList.size()<2) && exceptionHolder.isEmpty() && (loopCount<5)) { sleep(1000); loopCount++; } assertTrue("Threads did not finish in 5sec", loopCount<5); // if not -> they are in deadlock and the db did not detect it for (Exception exception : exceptionHolder) { - System.out.println("exception: "+exception.getMessage()); - exception.printStackTrace(); - } - if (exceptionHolder.size() > 0) { - assertTrue("It throws an exception in test => see sysout exception[0]=" + exceptionHolder.get(0).getMessage(), exceptionHolder.size() == 0); + log.error("exception: "+exception.getMessage(), exception); } + assertEquals("It throws an exception in test", 0, exceptionHolder.size()); + assertEquals("Thread(s) did not finish",2, statusList.size()); - assertTrue("Subscriber does not exists for identity=" + identity, NotificationsManager.getInstance().isSubscribed(identity, sc)); + assertTrue("Subscriber does not exists for identity=" + identity1, NotificationsManager.getInstance().isSubscribed(identity1, sc)); assertTrue("Subscriber does not exists for identity=" + identity2, NotificationsManager.getInstance().isSubscribed(identity2, sc)); codepointClient.close(); System.out.println("testConcurrentFindOrCreatePublisher finish successful"); JMSCodePointServerJunitHelper.stopServer(); - } /** diff --git a/src/test/java/org/olat/properties/PropertyTest.java b/src/test/java/org/olat/properties/PropertyTest.java index 2eb8577c66a5706a3a8712a00c2a5e10a3833a5e..7cc4c6aae80190256d42f6b352ecc82b3bc853a3 100644 --- a/src/test/java/org/olat/properties/PropertyTest.java +++ b/src/test/java/org/olat/properties/PropertyTest.java @@ -32,18 +32,19 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.List; +import java.util.UUID; + +import junit.framework.Assert; -import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.olat.core.commons.persistence.DBFactory; import org.olat.core.id.Identity; -import org.olat.core.id.OLATResourceable; +import org.olat.core.logging.OLog; import org.olat.core.logging.Tracing; import org.olat.group.BusinessGroup; import org.olat.group.BusinessGroupService; -import org.olat.resource.OLATResourceManager; import org.olat.test.JunitTestHelper; import org.olat.test.OlatTestCase; import org.springframework.beans.factory.annotation.Autowired; @@ -56,11 +57,10 @@ import org.springframework.beans.factory.annotation.Autowired; * Comment: * */ -public class PropertyTest extends OlatTestCase implements OLATResourceable { +public class PropertyTest extends OlatTestCase { + - private long RESOURCE_ID = 42; - private String RESOURCE_TYPE = "org.olat.properties.PropertyTest"; - private static Logger log = Logger.getLogger(PropertyTest.class); + private static OLog log = Tracing.createLoggerFor(PropertyTest.class); private static Identity identity = null, id2 = null, id3 = null, id4 = null; private static BusinessGroup group = null; private static org.olat.resource.OLATResource res = null; @@ -73,21 +73,17 @@ public class PropertyTest extends OlatTestCase implements OLATResourceable { /** * @see junit.framework.TestCase#setUp() */ - @Before public void setup() { + @Before + public void setup() { pm = PropertyManager.getInstance(); // identity with null User should be ok for test case - identity = JunitTestHelper.createAndPersistIdentityAsUser("foo"); - id2 = JunitTestHelper.createAndPersistIdentityAsUser("eis"); - id3 = JunitTestHelper.createAndPersistIdentityAsUser("zwoi"); - id4 = JunitTestHelper.createAndPersistIdentityAsUser("drp"); - OLATResourceManager orm = OLATResourceManager.getInstance(); - res = orm.findResourceable(this); - if (res == null) { - res = OLATResourceManager.getInstance().createOLATResourceInstance(this); - OLATResourceManager.getInstance().saveOLATResource(res); - } - + identity = JunitTestHelper.createAndPersistIdentityAsUser("foo-" + UUID.randomUUID().toString()); + id2 = JunitTestHelper.createAndPersistIdentityAsUser("eis-" + UUID.randomUUID().toString()); + id3 = JunitTestHelper.createAndPersistIdentityAsUser("zwoi-" + UUID.randomUUID().toString()); + id4 = JunitTestHelper.createAndPersistIdentityAsUser("drp-" + UUID.randomUUID().toString()); + res = JunitTestHelper.createRandomResource(); + List<BusinessGroup> l = businessGroupService.findBusinessGroupsOwnedBy(BusinessGroup.TYPE_BUDDYGROUP, identity, null); if (l.size() == 0) { group = businessGroupService.createBusinessGroup(identity, "a buddygroup", "a desc", BusinessGroup.TYPE_BUDDYGROUP, -1, -1, false, false, null); @@ -100,9 +96,10 @@ public class PropertyTest extends OlatTestCase implements OLATResourceable { /** * @see junit.framework.TestCase#tearDown() */ - @After public void tearDown() { + @After + public void tearDown() { try { - Tracing.logInfo("tearDown: DB.getInstance().closeSession()", this.getClass()); + log.info("tearDown: DB.getInstance().closeSession()"); DBFactory.getInstance().closeSession(); } catch (Exception e) { log.error("tearDown failed: ", e); @@ -133,18 +130,18 @@ public class PropertyTest extends OlatTestCase implements OLATResourceable { @Test public void testGetAllResourceTypeNames() { Property p = pm.createPropertyInstance(identity, group, res, "cat", "TestProperty", new Float(1.1), new Long(123456), "stringValue", "textValue"); try { - Tracing.logInfo("p='" + p +"'", this.getClass()); - Tracing.logInfo("res=" + res, this.getClass()); - Tracing.logInfo("res.getResourceableTypeName=" + res.getResourceableTypeName(), this.getClass()); + log.info("p='" + p +"'"); + log.info("res=" + res); + log.info("res.getResourceableTypeName=" + res.getResourceableTypeName()); pm.saveProperty(p); DBFactory.getInstance().closeSession(); - Tracing.logInfo("p='" + p +"'", this.getClass()); - Tracing.logInfo("res=" + res, this.getClass()); - Tracing.logInfo("res.getResourceableTypeName=" + res.getResourceableTypeName(), this.getClass()); + log.info("p='" + p +"'"); + log.info("res=" + res); + log.info("res.getResourceableTypeName=" + res.getResourceableTypeName()); String resTypeName = p.getResourceTypeName(); - Tracing.logInfo("resTypeName=" + resTypeName, this.getClass()); - List resTypeNames = pm.getAllResourceTypeNames(); - Tracing.logInfo("resTypeNames=" + resTypeNames, this.getClass()); + log.info("resTypeName=" + resTypeName); + List<String> resTypeNames = pm.getAllResourceTypeNames(); + log.info("resTypeNames=" + resTypeNames); assertTrue(resTypeNames.contains(resTypeName)); } finally { pm.deleteProperty(p); @@ -154,16 +151,17 @@ public class PropertyTest extends OlatTestCase implements OLATResourceable { /** * testListProperties */ - @Test public void testListProperties(){ + @Test + public void testListProperties(){ String resTypeName = res.getResourceableTypeName(); Long resTypeId = res.getResourceableId(); Property p = pm.createPropertyInstance(identity, group, res, "cat", "TestProperty", new Float(1.1), new Long(123456), "stringValue", "textValue"); pm.saveProperty(p); - List entries = PropertyManager.getInstance().listProperties(identity, group, resTypeName, resTypeId, "cat", "TestProperty"); + List<Property> entries = PropertyManager.getInstance().listProperties(identity, group, resTypeName, resTypeId, "cat", "TestProperty"); if(entries.size() == 1){ Property prop = (Property) entries.get(0); - assertTrue(resTypeName.equals(prop.getResourceTypeName())); - assertTrue(resTypeId.equals(prop.getResourceTypeId())); + assertEquals(resTypeName, prop.getResourceTypeName()); + assertEquals(resTypeId, prop.getResourceTypeId()); } pm.deleteProperty(p); @@ -209,8 +207,8 @@ public class PropertyTest extends OlatTestCase implements OLATResourceable { stop = System.currentTimeMillis(); System.out.println("CREATE generic property test: " + (stop-start) + " ms (" + (count * 1000 / (stop-start)) + "/sec)"); // some find identitites tests - List ids = pm.findIdentitiesWithProperty(null, null, "cat", "TestProperty", false); - assertTrue(ids.size() == count); + List<Identity> ids = pm.findIdentitiesWithProperty(null, null, "cat", "TestProperty", false); + assertEquals(count , ids.size()); // create course and user properties System.out.println("Preparing user/group properties test. Creating additional properties.."); @@ -229,6 +227,7 @@ public class PropertyTest extends OlatTestCase implements OLATResourceable { start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { Property p = pm.findProperty(identity, group, res, "cat", "TestProperty" + i); + assertNotNull(p); DBFactory.getInstance().closeSession(); } stop = System.currentTimeMillis(); @@ -239,6 +238,7 @@ public class PropertyTest extends OlatTestCase implements OLATResourceable { start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { Property p = pm.findUserProperty(identity, "cat", "TestProperty" + i); + assertNotNull(p); DBFactory.getInstance().closeSession(); } stop = System.currentTimeMillis(); @@ -263,6 +263,7 @@ public class PropertyTest extends OlatTestCase implements OLATResourceable { start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { Property p = pm.findUserProperty(identity, "cat", "TestProperty" + i); + assertNotNull(p); DBFactory.getInstance().closeSession(); } stop = System.currentTimeMillis(); @@ -277,6 +278,7 @@ public class PropertyTest extends OlatTestCase implements OLATResourceable { start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { Property p = pm.findUserProperty(identity, "cat", "TestProperty" + i); + Assert.assertNotNull(p); DBFactory.getInstance().closeSession(); } stop = System.currentTimeMillis(); @@ -370,35 +372,37 @@ public class PropertyTest extends OlatTestCase implements OLATResourceable { } @Test public void testFindIdentities() { - Property p = pm.createPropertyInstance(identity, group, res, "cat", "TestProperty", new Float(1.1), new Long(123456), "stringValue", "textValue"); + String propName = UUID.randomUUID().toString(); + + Property p = pm.createPropertyInstance(identity, group, res, "cat", propName, new Float(1.1), new Long(123456), "stringValue", "textValue"); pm.saveProperty(p); - p = pm.createPropertyInstance(id2, group, res, "cat", "TestProperty", new Float(1.1), new Long(123456), "stringValue", "textValue"); + p = pm.createPropertyInstance(id2, group, res, "cat", propName, new Float(1.1), new Long(123456), "stringValue", "textValue"); pm.saveProperty(p); - p = pm.createPropertyInstance(id3, group, res, "cat", "TestProperty", new Float(1.1), new Long(123456), "stringValue", "textValue"); + p = pm.createPropertyInstance(id3, group, res, "cat", propName, new Float(1.1), new Long(123456), "stringValue", "textValue"); pm.saveProperty(p); - p = pm.createPropertyInstance(id4, group, res, "cat", "TestProperty", new Float(1.1), new Long(123456), "stringValue", "textValue"); + p = pm.createPropertyInstance(id4, group, res, "cat", propName, new Float(1.1), new Long(123456), "stringValue", "textValue"); pm.saveProperty(p); - p = pm.createPropertyInstance(identity, group, res, "cat2", "TestProperty", new Float(1.1), new Long(123456), "stringValue", "textValue"); + p = pm.createPropertyInstance(identity, group, res, "cat2", propName, new Float(1.1), new Long(123456), "stringValue", "textValue"); pm.saveProperty(p); - p = pm.createPropertyInstance(id2, group, res, "cat2", "TestProperty", new Float(1.1), new Long(123456), "stringValue", "textValue"); + p = pm.createPropertyInstance(id2, group, res, "cat2", propName, new Float(1.1), new Long(123456), "stringValue", "textValue"); pm.saveProperty(p); DBFactory.getInstance().closeSession(); // now find identities - List ids = pm.findIdentitiesWithProperty(res, "cat", "TestProperty", false); - assertTrue(ids.size() == 4); - ids = pm.findIdentitiesWithProperty(res, "cat", "TestProperty", true); - assertTrue(ids.size() == 4); - ids = pm.findIdentitiesWithProperty(null, "cat", "TestProperty", false); - assertTrue(ids.size() == 4); - ids = pm.findIdentitiesWithProperty(null, "cat", "TestProperty", true); - assertTrue(ids.size() == 0); - ids = pm.findIdentitiesWithProperty(null, "cat2", "TestProperty", false); - assertTrue(ids.size() == 2); - ids = pm.findIdentitiesWithProperty(null, null, "TestProperty", false); - assertTrue(ids.size() == 4); // not 6, must be distinct - ids = pm.findIdentitiesWithProperty(null, null, "TestProperty", true); - assertTrue(ids.size() == 0); + List<Identity> ids = pm.findIdentitiesWithProperty(res, "cat", propName, false); + assertEquals(4, ids.size()); + ids = pm.findIdentitiesWithProperty(res, "cat", propName, true); + assertEquals(4, ids.size()); + ids = pm.findIdentitiesWithProperty(null, "cat", propName, false); + assertEquals(4, ids.size()); + ids = pm.findIdentitiesWithProperty(null, "cat", propName, true); + assertEquals(0, ids.size()); + ids = pm.findIdentitiesWithProperty(null, "cat2", propName, false); + assertEquals(2, ids.size()); + ids = pm.findIdentitiesWithProperty(null, null, propName, false); + assertEquals(4, ids.size()); // not 6, must be distinct + ids = pm.findIdentitiesWithProperty(null, null, propName, true); + assertEquals(0, ids.size()); } @Test public void testFindProperties() { @@ -409,7 +413,7 @@ public class PropertyTest extends OlatTestCase implements OLATResourceable { pm.saveProperty(p); p = pm.createPropertyInstance(id2, group, res, category, propertyName, new Float(1.1), new Long(123456), "stringValue", textValue); pm.saveProperty(p); - List propertyList = pm.findProperties(identity, group, res.getResourceableTypeName(), res.getResourceableId(), category, propertyName); + List<Property> propertyList = pm.findProperties(identity, group, res.getResourceableTypeName(), res.getResourceableId(), category, propertyName); assertEquals(1, propertyList.size()); assertEquals(propertyName, ((Property)propertyList.get(0)).getName() ); assertEquals(textValue, ((Property)propertyList.get(0)).getTextValue() ); @@ -428,18 +432,4 @@ public class PropertyTest extends OlatTestCase implements OLATResourceable { long stop = System.currentTimeMillis(); System.out.println("Ready : " + (stop-start) + " ms (" + ((l - count) * 1000 / (stop-start)) + "/sec)"); } - - /** - * @see org.olat.core.id.OLATResourceablegetResourceableTypeName() - */ - public String getResourceableTypeName() { - return RESOURCE_TYPE; - } - - /** - * @see org.olat.core.id.OLATResourceablegetResourceableId() - */ - public Long getResourceableId() { - return new Long(RESOURCE_ID); - } } diff --git a/src/test/java/org/olat/restapi/CatalogTest.java b/src/test/java/org/olat/restapi/CatalogTest.java index 17b798baf0c95d993e7091e0edc2fe4e079201e3..e933bd72be52e8526dbfbee86e97da048ed1e45f 100644 --- a/src/test/java/org/olat/restapi/CatalogTest.java +++ b/src/test/java/org/olat/restapi/CatalogTest.java @@ -180,8 +180,7 @@ public class CatalogTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - CatalogEntryVOes vos = parse(body, CatalogEntryVOes.class); + CatalogEntryVOes vos = conn.parse(response, CatalogEntryVOes.class); assertNotNull(vos); assertNotNull(vos.getCatalogEntries()); @@ -200,8 +199,7 @@ public class CatalogTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - CatalogEntryVO vo = parse(body, CatalogEntryVO.class); + CatalogEntryVO vo = conn.parse(response, CatalogEntryVO.class); assertNotNull(vo); assertEquals(entry1.getName(), vo.getName()); assertEquals(entry1.getDescription(), vo.getDescription()); @@ -237,8 +235,7 @@ public class CatalogTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - CatalogEntryVOes vos = parse(body, CatalogEntryVOes.class); + CatalogEntryVOes vos = conn.parse(response, CatalogEntryVOes.class); assertNotNull(vos); assertNotNull(vos.getCatalogEntries()); assertTrue(vos.getCatalogEntries().length <= 2); @@ -264,8 +261,7 @@ public class CatalogTest extends OlatJerseyTestCase { HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - CatalogEntryVO vo = parse(body, CatalogEntryVO.class); + CatalogEntryVO vo = conn.parse(response, CatalogEntryVO.class); assertNotNull(vo); CatalogManager catalogManager = CatalogManager.getInstance(); @@ -295,8 +291,7 @@ public class CatalogTest extends OlatJerseyTestCase { HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - CatalogEntryVO vo = parse(body, CatalogEntryVO.class); + CatalogEntryVO vo = conn.parse(response, CatalogEntryVO.class); assertNotNull(vo); CatalogManager catalogManager = CatalogManager.getInstance(); @@ -334,8 +329,7 @@ public class CatalogTest extends OlatJerseyTestCase { HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - CatalogEntryVO vo = parse(body, CatalogEntryVO.class); + CatalogEntryVO vo = conn.parse(response, CatalogEntryVO.class); assertNotNull(vo); CatalogManager catalogManager = CatalogManager.getInstance(); @@ -370,8 +364,7 @@ public class CatalogTest extends OlatJerseyTestCase { HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - CatalogEntryVO vo = parse(body, CatalogEntryVO.class); + CatalogEntryVO vo = conn.parse(response, CatalogEntryVO.class); assertNotNull(vo); CatalogManager catalogManager = CatalogManager.getInstance(); @@ -408,8 +401,7 @@ public class CatalogTest extends OlatJerseyTestCase { HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - CatalogEntryVO vo = parse(body, CatalogEntryVO.class); + CatalogEntryVO vo = conn.parse(response, CatalogEntryVO.class); assertNotNull(vo); CatalogManager catalogManager = CatalogManager.getInstance(); @@ -438,8 +430,7 @@ public class CatalogTest extends OlatJerseyTestCase { HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - CatalogEntryVO vo = parse(body, CatalogEntryVO.class); + CatalogEntryVO vo = conn.parse(response, CatalogEntryVO.class); assertNotNull(vo); CatalogManager catalogManager = CatalogManager.getInstance(); @@ -465,8 +456,7 @@ public class CatalogTest extends OlatJerseyTestCase { HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - CatalogEntryVO vo = parse(body, CatalogEntryVO.class); + CatalogEntryVO vo = conn.parse(response, CatalogEntryVO.class); assertNotNull(vo); CatalogManager catalogManager = CatalogManager.getInstance(); @@ -490,8 +480,7 @@ public class CatalogTest extends OlatJerseyTestCase { HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - CatalogEntryVO vo = parse(body, CatalogEntryVO.class); + CatalogEntryVO vo = conn.parse(response, CatalogEntryVO.class); assertNotNull(vo); CatalogManager catalogManager = CatalogManager.getInstance(); @@ -513,8 +502,7 @@ public class CatalogTest extends OlatJerseyTestCase { HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - CatalogEntryVO vo = parse(body, CatalogEntryVO.class); + CatalogEntryVO vo = conn.parse(response, CatalogEntryVO.class); assertNotNull(vo); CatalogManager catalogManager = CatalogManager.getInstance(); @@ -582,8 +570,7 @@ public class CatalogTest extends OlatJerseyTestCase { HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - UserVO vo = parse(body, UserVO.class); + UserVO vo = conn.parse(response, UserVO.class); assertNotNull(vo); //id1 is not owner diff --git a/src/test/java/org/olat/restapi/ContactsTest.java b/src/test/java/org/olat/restapi/ContactsTest.java index 6f276b03995234ab940080e52eea887517344ba9..47c636082ff367c4285109b7233597fa2207907e 100644 --- a/src/test/java/org/olat/restapi/ContactsTest.java +++ b/src/test/java/org/olat/restapi/ContactsTest.java @@ -25,7 +25,6 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; -import java.io.InputStream; import java.net.URISyntaxException; import java.util.List; @@ -202,8 +201,7 @@ public class ContactsTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(uri.build(), MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - UserVOes contacts = parse(body, UserVOes.class); + UserVOes contacts = conn.parse(response, UserVOes.class); assertNotNull(contacts); assertNotNull(contacts.getUsers()); assertEquals(1, contacts.getUsers().length); diff --git a/src/test/java/org/olat/restapi/CourseGroupMgmtTest.java b/src/test/java/org/olat/restapi/CourseGroupMgmtTest.java index cd40c594662f3183efca198b55adad8b64636194..e6241c629cfca4deed4337ac1c667c2a3aff29b6 100644 --- a/src/test/java/org/olat/restapi/CourseGroupMgmtTest.java +++ b/src/test/java/org/olat/restapi/CourseGroupMgmtTest.java @@ -36,6 +36,7 @@ import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; +import java.util.ArrayList; import java.util.List; import javax.ws.rs.core.MediaType; @@ -52,7 +53,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; import org.olat.basesecurity.BaseSecurity; -import org.olat.basesecurity.BaseSecurityManager; import org.olat.core.commons.persistence.DBFactory; import org.olat.core.id.Identity; import org.olat.core.id.OLATResourceable; @@ -91,6 +91,8 @@ public class CourseGroupMgmtTest extends OlatJerseyTestCase { @Autowired private BusinessGroupService businessGroupService; + @Autowired + private BaseSecurity securityManager; /** @@ -115,29 +117,21 @@ public class CourseGroupMgmtTest extends OlatJerseyTestCase { DBFactory.getInstance().saveObject(course); DBFactory.getInstance().closeSession(); - //create learn group - BaseSecurity secm = BaseSecurityManager.getInstance(); - - // 1) context one: learning groups - OLATResource c1 = JunitTestHelper.createRandomResource(); // create groups without waiting list - g1 = businessGroupService.createBusinessGroup(null, "rest-g1", null, BusinessGroup.TYPE_LEARNINGROUP, 0, 10, false, false, c1); - g2 = businessGroupService.createBusinessGroup(null, "rest-g2", null, BusinessGroup.TYPE_LEARNINGROUP, 0, 10, false, false, c1); + g1 = businessGroupService.createBusinessGroup(null, "rest-g1", null, BusinessGroup.TYPE_LEARNINGROUP, 0, 10, false, false, course); + g2 = businessGroupService.createBusinessGroup(null, "rest-g2", null, BusinessGroup.TYPE_LEARNINGROUP, 0, 10, false, false, course); // members - secm.addIdentityToSecurityGroup(id1, g2.getOwnerGroup()); - secm.addIdentityToSecurityGroup(id1, g1.getPartipiciantGroup()); - secm.addIdentityToSecurityGroup(id2, g1.getPartipiciantGroup()); - secm.addIdentityToSecurityGroup(id2, g2.getPartipiciantGroup()); + securityManager.addIdentityToSecurityGroup(id1, g2.getOwnerGroup()); + securityManager.addIdentityToSecurityGroup(id1, g1.getPartipiciantGroup()); + securityManager.addIdentityToSecurityGroup(id2, g1.getPartipiciantGroup()); + securityManager.addIdentityToSecurityGroup(id2, g2.getPartipiciantGroup()); - - // 2) context two: right groups - OLATResource c2 = JunitTestHelper.createRandomResource(); // groups - g3 = businessGroupService.createBusinessGroup(null, "rest-g3", null, BusinessGroup.TYPE_RIGHTGROUP, -1, -1, false, false, c2); - g4 = businessGroupService.createBusinessGroup(null, "rest-g4", null, BusinessGroup.TYPE_RIGHTGROUP, -1, -1, false, false, c2); + g3 = businessGroupService.createBusinessGroup(null, "rest-g3", null, BusinessGroup.TYPE_RIGHTGROUP, -1, -1, false, false, course); + g4 = businessGroupService.createBusinessGroup(null, "rest-g4", null, BusinessGroup.TYPE_RIGHTGROUP, -1, -1, false, false, course); // members - secm.addIdentityToSecurityGroup(id1, g3.getPartipiciantGroup()); - secm.addIdentityToSecurityGroup(id2, g4.getPartipiciantGroup()); + securityManager.addIdentityToSecurityGroup(id1, g3.getPartipiciantGroup()); + securityManager.addIdentityToSecurityGroup(id2, g4.getPartipiciantGroup()); DBFactory.getInstance().closeSession(); // simulate user clicks } @@ -151,7 +145,6 @@ public class CourseGroupMgmtTest extends OlatJerseyTestCase { DBFactory.getInstance().closeSession(); } catch (Exception e) { log.error("Exception in tearDown(): " + e); - e.printStackTrace(); throw e; } } @@ -168,9 +161,16 @@ public class CourseGroupMgmtTest extends OlatJerseyTestCase { List<GroupVO> vos = parseGroupArray(body); assertNotNull(vos); - assertEquals(2, vos.size());//g1 and g2 - assertTrue(vos.get(0).getKey().equals(g1.getKey()) || vos.get(0).getKey().equals(g2.getKey())); - assertTrue(vos.get(1).getKey().equals(g1.getKey()) || vos.get(1).getKey().equals(g2.getKey())); + assertEquals(2, vos.size());//g1, g2, g3, g4 + + List<Long> voKeys = new ArrayList<Long>(4); + for(GroupVO vo:vos) { + voKeys.add(vo.getKey()); + } + assertTrue(voKeys.contains(g1.getKey())); + assertTrue(voKeys.contains(g2.getKey())); + //assertTrue(voKeys.contains(g3.getKey())); + //assertTrue(voKeys.contains(g4.getKey())); } @Test @@ -180,9 +180,8 @@ public class CourseGroupMgmtTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - GroupVO vo = parse(body, GroupVO.class); + GroupVO vo = conn.parse(response, GroupVO.class); assertNotNull(vo); assertEquals(g1.getKey(), vo.getKey()); } @@ -203,9 +202,8 @@ public class CourseGroupMgmtTest extends OlatJerseyTestCase { HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - GroupVO responseVo = parse(body, GroupVO.class); + GroupVO responseVo = conn.parse(response, GroupVO.class); assertNotNull(responseVo); assertEquals(vo.getName(), responseVo.getName()); diff --git a/src/test/java/org/olat/restapi/CourseSecurityTest.java b/src/test/java/org/olat/restapi/CourseSecurityTest.java index 09297b903f1f366fac1a6df592c7a24bdbc74913..19a205f11717360dbb20eeff3e4fcca5bbffb626 100644 --- a/src/test/java/org/olat/restapi/CourseSecurityTest.java +++ b/src/test/java/org/olat/restapi/CourseSecurityTest.java @@ -40,6 +40,7 @@ import javax.ws.rs.core.UriBuilder; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPut; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.olat.admin.securitygroup.gui.IdentitiesAddEvent; @@ -83,8 +84,11 @@ public class CourseSecurityTest extends OlatJerseyTestCase { // create course and persist as OLATResourceImpl admin = BaseSecurityManager.getInstance().findIdentityByName("administrator"); id1 = JunitTestHelper.createAndPersistIdentityAsUser("id-c-s-0"); + Assert.assertNotNull(id1); auth1 = JunitTestHelper.createAndPersistIdentityAsAuthor("id-c-s-1"); + Assert.assertNotNull(auth1); auth2 = JunitTestHelper.createAndPersistIdentityAsAuthor("id-c-s-2"); + Assert.assertNotNull(auth2); course = CoursesWebService.createEmptyCourse(admin, "course-security-2", "Test course for the security test", null); DBFactory.getInstance().intermediateCommit(); diff --git a/src/test/java/org/olat/restapi/CoursesContactElementTest.java b/src/test/java/org/olat/restapi/CoursesContactElementTest.java index bf286ef6a11a7e794bcc01857eb3bf3ed9218f8c..7fa2f00f8d0b0e72ba4ee838fb40374a933b0157 100644 --- a/src/test/java/org/olat/restapi/CoursesContactElementTest.java +++ b/src/test/java/org/olat/restapi/CoursesContactElementTest.java @@ -36,7 +36,6 @@ import static org.olat.course.nodes.co.COEditController.CONFIG_KEY_MBODY_DEFAULT import static org.olat.course.nodes.co.COEditController.CONFIG_KEY_MSUBJECT_DEFAULT; import java.io.IOException; -import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.List; @@ -115,11 +114,9 @@ public class CoursesContactElementTest extends OlatJerseyTestCase { .queryParam("objectives", "Contact-objectives-0").build(); HttpPut method = conn.createPut(newContactUri, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); - InputStream body = response.getEntity().getContent(); - assertEquals(200, response.getStatusLine().getStatusCode()); - CourseNodeVO contactNode = parse(body, CourseNodeVO.class); + CourseNodeVO contactNode = conn.parse(response, CourseNodeVO.class); assertNotNull(contactNode); assertNotNull(contactNode.getId()); assertEquals(contactNode.getShortTitle(), "Contact-0"); @@ -148,12 +145,10 @@ public class CoursesContactElementTest extends OlatJerseyTestCase { .build(); HttpPut method = conn.createPut(newContactUri, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); - InputStream body = response.getEntity().getContent(); - //check the return values assertEquals(200, response.getStatusLine().getStatusCode()); - CourseNodeVO contactNode = parse(body, CourseNodeVO.class); + CourseNodeVO contactNode = conn.parse(response, CourseNodeVO.class); assertNotNull(contactNode); assertNotNull(contactNode.getId()); diff --git a/src/test/java/org/olat/restapi/CoursesElementsTest.java b/src/test/java/org/olat/restapi/CoursesElementsTest.java index 52c6ca3ccb6eb27bd9748366f395da95ebf46302..09ce1ceb94ca7110ace068415611f544f967e30f 100644 --- a/src/test/java/org/olat/restapi/CoursesElementsTest.java +++ b/src/test/java/org/olat/restapi/CoursesElementsTest.java @@ -32,7 +32,6 @@ import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; -import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; @@ -115,9 +114,8 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - CourseVO course = parse(body, CourseVO.class); + CourseVO course = conn.parse(response, CourseVO.class); assertNotNull(course); assertNotNull(course.getKey()); assertNotNull(course.getEditorRootNodeId()); @@ -133,8 +131,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpResponse newStructureCode = conn.execute(newStructureMethod); assertTrue(newStructureCode.getStatusLine().getStatusCode() == 200 || newStructureCode.getStatusLine().getStatusCode() == 201); - String newStructureBody = EntityUtils.toString(newStructureCode.getEntity()); - CourseNodeVO structureNode = parse(newStructureBody, CourseNodeVO.class); + CourseNodeVO structureNode = conn.parse(newStructureCode, CourseNodeVO.class); assertNotNull(structureNode); assertNotNull(structureNode.getId()); assertEquals(structureNode.getShortTitle(), "Structure-0"); @@ -164,8 +161,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpResponse newPageCode = conn.execute(newPageMethod); assertTrue(newPageCode.getStatusLine().getStatusCode() == 200 || newPageCode.getStatusLine().getStatusCode() == 201); - String newPageBody = EntityUtils.toString(newPageCode.getEntity()); - CourseNodeVO pageNode = parse(newPageBody, CourseNodeVO.class); + CourseNodeVO pageNode = conn.parse(newPageCode, CourseNodeVO.class); assertNotNull(pageNode); assertNotNull(pageNode.getId()); assertEquals(pageNode.getShortTitle(), "Single-Page-0"); @@ -190,8 +186,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpResponse newFolderCode = conn.execute(newFolderMethod); assertTrue(newFolderCode.getStatusLine().getStatusCode() == 200 || newFolderCode.getStatusLine().getStatusCode() == 201); - String newFolderBody = EntityUtils.toString(newFolderCode.getEntity()); - CourseNodeVO folderNode = parse(newFolderBody, CourseNodeVO.class); + CourseNodeVO folderNode = conn.parse(newFolderCode, CourseNodeVO.class); assertNotNull(folderNode); assertNotNull(folderNode.getId()); assertEquals(folderNode.getShortTitle(), "Folder-0"); @@ -210,8 +205,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { new BasicNameValuePair("objectives", "Forum-objectives-0")); HttpResponse newForumCode = conn.execute(newForumMethod); assertTrue(newForumCode.getStatusLine().getStatusCode() == 200 || newForumCode.getStatusLine().getStatusCode() == 201); - String newForumBody = EntityUtils.toString(newForumCode.getEntity()); - CourseNodeVO forumNode = parse(newForumBody, CourseNodeVO.class); + CourseNodeVO forumNode = conn.parse(newForumCode, CourseNodeVO.class); assertNotNull(forumNode); assertNotNull(forumNode.getId()); assertEquals(forumNode.getShortTitle(), "Forum-0"); @@ -232,8 +226,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { new BasicNameValuePair("text", "A very difficult test")); HttpResponse newTaskCode = conn.execute(newTaskMethod); assertTrue(newTaskCode.getStatusLine().getStatusCode() == 200 || newTaskCode.getStatusLine().getStatusCode() == 201); - String newTaskBody = EntityUtils.toString(newTaskCode.getEntity()); - CourseNodeVO taskNode = parse(newTaskBody, CourseNodeVO.class); + CourseNodeVO taskNode = conn.parse(newTaskCode, CourseNodeVO.class); assertNotNull(taskNode); assertNotNull(taskNode.getId()); assertEquals(taskNode.getShortTitle(), "Task-0"); @@ -275,8 +268,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { new BasicNameValuePair("objectives", "Assessment-objectives-0")); HttpResponse newAssessmentCode = conn.execute(newAssessmentMethod); assertTrue(newAssessmentCode.getStatusLine().getStatusCode() == 200 || newAssessmentCode.getStatusLine().getStatusCode() == 201); - String newAssessmentBody = EntityUtils.toString(newAssessmentCode.getEntity()); - CourseNodeVO assessmentNode = parse(newAssessmentBody, CourseNodeVO.class); + CourseNodeVO assessmentNode = conn.parse(newAssessmentCode, CourseNodeVO.class); assertNotNull(assessmentNode); assertNotNull(assessmentNode.getId()); assertEquals(assessmentNode.getShortTitle(), "Assessment-0"); @@ -295,8 +287,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpResponse newContactCode = conn.execute(newContactMethod); assertEquals(200, newContactCode.getStatusLine().getStatusCode()); - String newContactBody = EntityUtils.toString(newContactCode.getEntity()); - CourseNodeVO contactNode = parse(newContactBody, CourseNodeVO.class); + CourseNodeVO contactNode = conn.parse(newContactCode, CourseNodeVO.class); assertNotNull(contactNode); assertNotNull(contactNode.getId()); assertEquals(contactNode.getShortTitle(), "Contact-0"); @@ -315,9 +306,8 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - CourseVO course = parse(body, CourseVO.class); + CourseVO course = conn.parse(response, CourseVO.class); assertNotNull(course); assertNotNull(course.getKey()); assertNotNull(course.getEditorRootNodeId()); @@ -342,9 +332,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpResponse newGrpCode = conn.execute(newGrpMethod); assertEquals(200, newGrpCode.getStatusLine().getStatusCode()); - InputStream newGrpBody = newGrpCode.getEntity().getContent(); - - GroupVO group = parse(newGrpBody, GroupVO.class); + GroupVO group = conn.parse(newGrpCode, GroupVO.class); assertNotNull(group); assertNotNull(group.getKey()); @@ -358,8 +346,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpPut newStructureMethod = conn.createPut(newStructureUri, MediaType.APPLICATION_JSON, true); HttpResponse newStructureCode = conn.execute(newStructureMethod); assertTrue(newStructureCode.getStatusLine().getStatusCode() == 200 || newStructureCode.getStatusLine().getStatusCode() == 201); - String newStructureBody = EntityUtils.toString(newStructureCode.getEntity()); - CourseNodeVO structureNode = parse(newStructureBody, CourseNodeVO.class); + CourseNodeVO structureNode = conn.parse(newStructureCode, CourseNodeVO.class); assertNotNull(structureNode); assertNotNull(structureNode.getId()); assertEquals(structureNode.getShortTitle(), "Structure-0"); @@ -384,8 +371,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpResponse newPageCode = conn.execute(newPageMethod); assertTrue(newPageCode.getStatusLine().getStatusCode() == 200 || newPageCode.getStatusLine().getStatusCode() == 201); - String newPageBody = EntityUtils.toString(newPageCode.getEntity()); - CourseNodeVO pageNode = parse(newPageBody, CourseNodeVO.class); + CourseNodeVO pageNode = conn.parse(newPageCode, CourseNodeVO.class); assertNotNull(pageNode); assertNotNull(pageNode.getId()); assertEquals(pageNode.getShortTitle(), "Single-Page-0"); @@ -403,8 +389,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpPut newFolderMethod = conn.createPut(newFolderUri, MediaType.APPLICATION_JSON, true); HttpResponse newFolderCode = conn.execute(newFolderMethod); assertTrue(newFolderCode.getStatusLine().getStatusCode() == 200 || newFolderCode.getStatusLine().getStatusCode() == 201); - String newFolderBody = EntityUtils.toString(newFolderCode.getEntity()); - CourseNodeVO folderNode = parse(newFolderBody, CourseNodeVO.class); + CourseNodeVO folderNode = conn.parse(newFolderCode, CourseNodeVO.class); assertNotNull(folderNode); assertNotNull(folderNode.getId()); assertEquals(folderNode.getShortTitle(), "Folder-0"); @@ -422,8 +407,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpPut newForumMethod = conn.createPut(newForumUri, MediaType.APPLICATION_JSON, true); HttpResponse newForumCode = conn.execute(newForumMethod); assertTrue(newForumCode.getStatusLine().getStatusCode() == 200 || newForumCode.getStatusLine().getStatusCode() == 201); - String newForumBody = EntityUtils.toString(newForumCode.getEntity()); - CourseNodeVO forumNode = parse(newForumBody, CourseNodeVO.class); + CourseNodeVO forumNode = conn.parse(newForumCode, CourseNodeVO.class); assertNotNull(forumNode); assertNotNull(forumNode.getId()); assertEquals(forumNode.getShortTitle(), "Forum-0"); @@ -442,8 +426,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpPut newTaskMethod = conn.createPut(newTaskUri, MediaType.APPLICATION_JSON, true); HttpResponse newTaskCode = conn.execute(newTaskMethod); assertTrue(newTaskCode.getStatusLine().getStatusCode() == 200 || newTaskCode.getStatusLine().getStatusCode() == 201); - String newTaskBody = EntityUtils.toString(newTaskCode.getEntity()); - CourseNodeVO taskNode = parse(newTaskBody, CourseNodeVO.class); + CourseNodeVO taskNode = conn.parse(newTaskCode, CourseNodeVO.class); assertNotNull(taskNode); assertNotNull(taskNode.getId()); assertEquals(taskNode.getShortTitle(), "Task-0"); @@ -467,8 +450,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpGet getTaskConfig = conn.createGet(taskConfigUri, MediaType.APPLICATION_JSON, true); taskConfigCode = conn.execute(getTaskConfig); assertTrue(taskConfigCode.getStatusLine().getStatusCode() == 200 || taskConfigCode.getStatusLine().getStatusCode() == 201); - String taskConfigBody = EntityUtils.toString(taskConfigCode.getEntity()); - TaskConfigVO taskConfig = parse(taskConfigBody, TaskConfigVO.class); + TaskConfigVO taskConfig = conn.parse(taskConfigCode, TaskConfigVO.class); assertNotNull(taskConfig); assertTrue(!taskConfig.getIsAssignmentEnabled());//default is true assertTrue(taskConfig.getIsScoringEnabled() & taskConfig.getIsScoringGranted()); @@ -484,8 +466,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpPut newAssessmentMethod = conn.createPut(newAssessmentUri, MediaType.APPLICATION_JSON, true); HttpResponse newAssessmentCode = conn.execute(newAssessmentMethod); assertTrue(newAssessmentCode.getStatusLine().getStatusCode() == 200 || newAssessmentCode.getStatusLine().getStatusCode() == 201); - String newAssessmentBody = EntityUtils.toString(newAssessmentCode.getEntity()); - CourseNodeVO assessmentNode = parse(newAssessmentBody, CourseNodeVO.class); + CourseNodeVO assessmentNode = conn.parse(newAssessmentCode, CourseNodeVO.class); assertNotNull(assessmentNode); assertNotNull(assessmentNode.getId()); assertEquals(assessmentNode.getShortTitle(), "Assessment-0"); @@ -502,8 +483,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpPut newContactMethod = conn.createPut(newContactUri, MediaType.APPLICATION_JSON, true); HttpResponse newContactCode = conn.execute(newContactMethod); assertEquals(200, newContactCode.getStatusLine().getStatusCode()); - String newContactBody = EntityUtils.toString(newContactCode.getEntity()); - CourseNodeVO contactNode = parse(newContactBody, CourseNodeVO.class); + CourseNodeVO contactNode = conn.parse(newContactCode, CourseNodeVO.class); assertNotNull(contactNode); assertNotNull(contactNode.getId()); assertEquals(contactNode.getShortTitle(), "Contact-0"); @@ -535,9 +515,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { newENCode = conn.execute(newENMethod); assertEquals(200, newENCode.getStatusLine().getStatusCode()); - - String newENBody = EntityUtils.toString(newENCode.getEntity()); - CourseNodeVO enNode = parse(newENBody, CourseNodeVO.class); + CourseNodeVO enNode = conn.parse(newENCode, CourseNodeVO.class); assertNotNull(enNode); assertNotNull(enNode.getId()); assertEquals(enNode.getShortTitle(), "Enrollment-0"); @@ -562,9 +540,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpResponse qtiRepoCode = conn.execute(qtiRepoMethod); assertTrue(qtiRepoCode.getStatusLine().getStatusCode() == 200 || qtiRepoCode.getStatusLine().getStatusCode() == 201); - - String qtiRepoBody = EntityUtils.toString(qtiRepoCode.getEntity()); - RepositoryEntryVO newTestVO = parse(qtiRepoBody, RepositoryEntryVO.class); + RepositoryEntryVO newTestVO = conn.parse(qtiRepoCode, RepositoryEntryVO.class); assertNotNull(newTestVO); Long key = newTestVO.getKey(); @@ -583,8 +559,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpPut newTestMethod = conn.createPut(newTestUri, MediaType.APPLICATION_JSON, true); HttpResponse newTestCode = conn.execute(newTestMethod); assertTrue(newTestCode.getStatusLine().getStatusCode() == 200 || newTestCode.getStatusLine().getStatusCode() == 201); - String newTestBody = EntityUtils.toString(newTestCode.getEntity()); - CourseNodeVO testNode = parse(newTestBody, CourseNodeVO.class); + CourseNodeVO testNode = conn.parse(newTestCode, CourseNodeVO.class); assertNotNull(testNode); assertNotNull(testNode.getId()); assertEquals(testNode.getShortTitle(), "Test-0"); @@ -617,8 +592,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpGet getTestConfig = conn.createGet(testConfigUri, MediaType.APPLICATION_JSON, true); testConfigCode = conn.execute(getTestConfig); assertTrue(testConfigCode.getStatusLine().getStatusCode() == 200 || testConfigCode.getStatusLine().getStatusCode() == 201); - String testConfigBody = EntityUtils.toString(testConfigCode.getEntity()); - TestConfigVO testConfig = parse(testConfigBody, TestConfigVO.class); + TestConfigVO testConfig = conn.parse(testConfigCode, TestConfigVO.class); assertTrue(testConfig.getNumAttempts() == 10); assertTrue(testConfig.getAllowCancel()); assertTrue(testConfig.getSummeryPresentation().equals(AssessmentInstance.QMD_ENTRY_SUMMARY_DETAILED)); @@ -640,8 +614,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpResponse surveyRepoCode = conn.execute(surveyRepoMethod); assertTrue(surveyRepoCode.getStatusLine().getStatusCode() == 200 || surveyRepoCode.getStatusLine().getStatusCode() == 201); - String surveyRepoBody = EntityUtils.toString(surveyRepoCode.getEntity()); - RepositoryEntryVO newSurveyVO = parse(surveyRepoBody, RepositoryEntryVO.class); + RepositoryEntryVO newSurveyVO = conn.parse(surveyRepoCode, RepositoryEntryVO.class); assertNotNull(newSurveyVO); Long surveyKey = newSurveyVO.getKey(); @@ -660,8 +633,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpPut newSurveyMethod = conn.createPut(newSurveyUri, MediaType.APPLICATION_JSON, true); HttpResponse newSurveyCode = conn.execute(newSurveyMethod); assertTrue(newSurveyCode.getStatusLine().getStatusCode() == 200 || newSurveyCode.getStatusLine().getStatusCode() == 201); - String newSurveyBody = EntityUtils.toString(newSurveyCode.getEntity()); - CourseNodeVO surveyNode = parse(newSurveyBody, CourseNodeVO.class); + CourseNodeVO surveyNode = conn.parse(newSurveyCode, CourseNodeVO.class); assertNotNull(surveyNode); assertNotNull(surveyNode.getId()); assertEquals(surveyNode.getShortTitle(), "Survey-0"); @@ -685,8 +657,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpGet getSurveyConfig = conn.createGet(surveykConfigUri, MediaType.APPLICATION_JSON, true); surveyConfigCode = conn.execute(getSurveyConfig); assertTrue(surveyConfigCode.getStatusLine().getStatusCode() == 200 || surveyConfigCode.getStatusLine().getStatusCode() == 201); - String surveyConfigBody =EntityUtils.toString(surveyConfigCode.getEntity()); - SurveyConfigVO surveyConfig = parse(surveyConfigBody, SurveyConfigVO.class); + SurveyConfigVO surveyConfig = conn.parse(surveyConfigCode, SurveyConfigVO.class); assertNotNull(surveyConfig); assertTrue(surveyConfig.getAllowCancel()); @@ -702,9 +673,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpResponse newTUCode = conn.execute(newTUMethod); assertEquals(200, newTUCode.getStatusLine().getStatusCode()); - - String newTUBody = EntityUtils.toString(newTUCode.getEntity()); - CourseNodeVO tuNode = parse(newTUBody, CourseNodeVO.class); + CourseNodeVO tuNode = conn.parse(newTUCode, CourseNodeVO.class); assertNotNull(tuNode); assertNotNull(tuNode.getId()); assertEquals(tuNode.getShortTitle(), "ExternalPage-0"); @@ -799,9 +768,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - - CourseVO course = parse(body, CourseVO.class); + CourseVO course = conn.parse(response, CourseVO.class); assertNotNull(course); assertNotNull(course.getKey()); assertNotNull(course.getEditorRootNodeId()); @@ -819,8 +786,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpResponse newStructureCode = conn.execute(updateMethod); assertTrue(newStructureCode.getStatusLine().getStatusCode() == 200 || newStructureCode.getStatusLine().getStatusCode() == 201); //check the response - String newStructureBody = EntityUtils.toString(newStructureCode.getEntity()); - CourseNodeVO structureNode = parse(newStructureBody, CourseNodeVO.class); + CourseNodeVO structureNode = conn.parse(newStructureCode, CourseNodeVO.class); assertNotNull(structureNode); assertNotNull(structureNode.getId()); assertEquals(structureNode.getShortTitle(), "Structure-0b"); @@ -850,9 +816,8 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - - CourseVO course = parse(body, CourseVO.class); + + CourseVO course = conn.parse(response, CourseVO.class); assertNotNull(course); assertNotNull(course.getKey()); assertNotNull(course.getEditorRootNodeId()); @@ -881,8 +846,7 @@ public class CoursesElementsTest extends OlatJerseyTestCase { HttpResponse newStructureCode = conn.execute(newStructureMethod); assertTrue(newStructureCode.getStatusLine().getStatusCode() == 200 || newStructureCode.getStatusLine().getStatusCode() == 201); //check the response - String newStructureBody = EntityUtils.toString(newStructureCode.getEntity()); - CourseNodeVO structureNode = parse(newStructureBody, CourseNodeVO.class); + CourseNodeVO structureNode = conn.parse(newStructureCode, CourseNodeVO.class); assertNotNull(structureNode); assertNotNull(structureNode.getId()); assertEquals(structureNode.getShortTitle(), "Structure-0-with-file"); diff --git a/src/test/java/org/olat/restapi/CoursesTest.java b/src/test/java/org/olat/restapi/CoursesTest.java index 61abfc7b64983a93d459faf440d8c9be3de0d547..0bb41bae64e28a5e57669a8d3ee77deac9db3486 100644 --- a/src/test/java/org/olat/restapi/CoursesTest.java +++ b/src/test/java/org/olat/restapi/CoursesTest.java @@ -138,8 +138,7 @@ public class CoursesTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - CourseVOes courses = parse(body, CourseVOes.class); + CourseVOes courses = conn.parse(response, CourseVOes.class); assertNotNull(courses); assertNotNull(courses.getCourses()); assertEquals(1, courses.getCourses().length); @@ -155,8 +154,7 @@ public class CoursesTest extends OlatJerseyTestCase { HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - CourseVO course = parse(body, CourseVO.class); + CourseVO course = conn.parse(response, CourseVO.class); assertNotNull(course); assertEquals("course3", course.getTitle()); //check repository entry diff --git a/src/test/java/org/olat/restapi/ForumTest.java b/src/test/java/org/olat/restapi/ForumTest.java index 88290e29853f37d9d2315f5133a3511108c03888..965538135034dbf56b3a4a073907fb531958422b 100644 --- a/src/test/java/org/olat/restapi/ForumTest.java +++ b/src/test/java/org/olat/restapi/ForumTest.java @@ -163,8 +163,7 @@ public class ForumTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - MessageVOes threads = parse(body, MessageVOes.class); + MessageVOes threads = conn.parse(response, MessageVOes.class); assertNotNull(threads); assertNotNull(threads.getMessages()); @@ -195,8 +194,7 @@ public class ForumTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - MessageVOes threads = parse(body, MessageVOes.class); + MessageVOes threads = conn.parse(response, MessageVOes.class); assertNotNull(threads); assertNotNull(threads.getMessages()); @@ -210,12 +208,10 @@ public class ForumTest extends OlatJerseyTestCase { URI uri = getForumUriBuilder().path("threads").queryParam("authorKey", id1.getKey()) .queryParam("title", "New thread") .queryParam("body", "A very interesting thread").build(); - HttpPut method = conn.createPut( -uri, MediaType.APPLICATION_JSON, true); + HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - MessageVO thread = parse(body, MessageVO.class); + MessageVO thread = conn.parse(response, MessageVO.class); assertNotNull(thread); assertNotNull(thread.getKey()); assertEquals(thread.getForumKey(), forum.getKey()); @@ -244,8 +240,7 @@ uri, MediaType.APPLICATION_JSON, true); HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - MessageVO message = parse(body, MessageVO.class); + MessageVO message = conn.parse(response, MessageVO.class); assertNotNull(message); assertNotNull(message.getKey()); assertEquals(message.getForumKey(), forum.getKey()); @@ -311,8 +306,7 @@ uri, MediaType.APPLICATION_JSON, true); HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - MessageVO message = parse(body, MessageVO.class); + MessageVO message = conn.parse(response, MessageVO.class); assertNotNull(message); //attachment @@ -355,8 +349,7 @@ uri, MediaType.APPLICATION_JSON, true); HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - MessageVO message = parse(body, MessageVO.class); + MessageVO message = conn.parse(response, MessageVO.class); assertNotNull(message); //attachment @@ -420,8 +413,7 @@ uri, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - MessageVO message = parse(body, MessageVO.class); + MessageVO message = conn.parse(response, MessageVO.class); assertNotNull(message); assertNotNull(message.getAttachments()); @@ -470,8 +462,7 @@ uri, MediaType.APPLICATION_JSON, true); HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - MessageVO message = parse(body, MessageVO.class); + MessageVO message = conn.parse(response, MessageVO.class); assertNotNull(message); //attachment @@ -521,8 +512,7 @@ uri, MediaType.APPLICATION_JSON, true); HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - MessageVO message = parse(body, MessageVO.class); + MessageVO message = conn.parse(response, MessageVO.class); assertNotNull(message); //attachment diff --git a/src/test/java/org/olat/restapi/GroupFoldersTest.java b/src/test/java/org/olat/restapi/GroupFoldersTest.java index 37311683f3962ce190565789967a008f1c1a4d12..a7abb36bc48ee85f42ead457d6449a9d8e9f4fbf 100644 --- a/src/test/java/org/olat/restapi/GroupFoldersTest.java +++ b/src/test/java/org/olat/restapi/GroupFoldersTest.java @@ -327,8 +327,7 @@ public class GroupFoldersTest extends OlatJerseyTestCase { HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - FileVO file = parse(body, FileVO.class); + FileVO file = conn.parse(response, FileVO.class); assertNotNull(file); } @@ -345,8 +344,7 @@ public class GroupFoldersTest extends OlatJerseyTestCase { HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - FileVO file = parse(body, FileVO.class); + FileVO file = conn.parse(response, FileVO.class); assertNotNull(file); assertNotNull(file.getHref()); assertNotNull(file.getTitle()); diff --git a/src/test/java/org/olat/restapi/GroupMgmtTest.java b/src/test/java/org/olat/restapi/GroupMgmtTest.java index 99bb0396d8b54cb0dd4b4e7c0604b929d3afc1e8..d3e68c62c6225fecae38ab7d2edf945315de95fa 100644 --- a/src/test/java/org/olat/restapi/GroupMgmtTest.java +++ b/src/test/java/org/olat/restapi/GroupMgmtTest.java @@ -320,9 +320,7 @@ public class GroupMgmtTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - - GroupVO vo = parse(body, GroupVO.class); + GroupVO vo = conn.parse(response, GroupVO.class); assertNotNull(vo); assertEquals(vo.getKey(), g1.getKey()); } @@ -335,9 +333,7 @@ public class GroupMgmtTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - - GroupInfoVO vo = parse(body, GroupInfoVO.class); + GroupInfoVO vo = conn.parse(response, GroupInfoVO.class); assertNotNull(vo); assertEquals(Boolean.TRUE, vo.getHasWiki()); assertEquals("<p>Hello world</p>", vo.getNews()); @@ -353,9 +349,7 @@ public class GroupMgmtTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - - GroupInfoVO vo = parse(body, GroupInfoVO.class); + GroupInfoVO vo = conn.parse(response, GroupInfoVO.class); assertNotNull(vo); assertEquals(Boolean.FALSE, vo.getHasWiki()); assertNull(vo.getNews()); diff --git a/src/test/java/org/olat/restapi/RepositoryEntriesTest.java b/src/test/java/org/olat/restapi/RepositoryEntriesTest.java index 19826f420f6b2b6424be37436a7ac86e582af55a..98ee5a2333fb940b6b5f3fcea9adb8da03d53a7c 100644 --- a/src/test/java/org/olat/restapi/RepositoryEntriesTest.java +++ b/src/test/java/org/olat/restapi/RepositoryEntriesTest.java @@ -111,8 +111,7 @@ public class RepositoryEntriesTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - RepositoryEntryVOes entryVoes = parse(body, RepositoryEntryVOes.class); + RepositoryEntryVOes entryVoes = conn.parse(response, RepositoryEntryVOes.class); assertNotNull(entryVoes); @@ -131,10 +130,7 @@ public class RepositoryEntriesTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - - - RepositoryEntryVO entryVo = parse(body, RepositoryEntryVO.class); + RepositoryEntryVO entryVo = conn.parse(response, RepositoryEntryVO.class); assertNotNull(entryVo); } @@ -158,10 +154,7 @@ public class RepositoryEntriesTest extends OlatJerseyTestCase { HttpResponse response = conn.execute(method); assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201); - - InputStream body = response.getEntity().getContent(); - - RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class); + RepositoryEntryVO vo = conn.parse(response, RepositoryEntryVO.class); assertNotNull(vo); Long key = vo.getKey(); @@ -193,10 +186,7 @@ public class RepositoryEntriesTest extends OlatJerseyTestCase { HttpResponse response = conn.execute(method); assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201); - - InputStream body = response.getEntity().getContent(); - - RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class); + RepositoryEntryVO vo = conn.parse(response, RepositoryEntryVO.class); assertNotNull(vo); Long key = vo.getKey(); @@ -229,10 +219,7 @@ public class RepositoryEntriesTest extends OlatJerseyTestCase { HttpResponse response = conn.execute(method); assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201); - - InputStream body = response.getEntity().getContent(); - - RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class); + RepositoryEntryVO vo = conn.parse(response, RepositoryEntryVO.class); assertNotNull(vo); Long key = vo.getKey(); @@ -264,10 +251,7 @@ public class RepositoryEntriesTest extends OlatJerseyTestCase { HttpResponse response = conn.execute(method); assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201); - - InputStream body = response.getEntity().getContent(); - - RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class); + RepositoryEntryVO vo = conn.parse(response, RepositoryEntryVO.class); assertNotNull(vo); Long key = vo.getKey(); @@ -300,10 +284,7 @@ public class RepositoryEntriesTest extends OlatJerseyTestCase { HttpResponse response = conn.execute(method); assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201); - - InputStream body = response.getEntity().getContent(); - - RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class); + RepositoryEntryVO vo = conn.parse(response, RepositoryEntryVO.class); assertNotNull(vo); Long key = vo.getKey(); diff --git a/src/test/java/org/olat/restapi/UserAuthenticationMgmtTest.java b/src/test/java/org/olat/restapi/UserAuthenticationMgmtTest.java index 0ab5d398117501b1bea643a5033cb7855b158184..3cb8b5759bb7cb27c3912b8c3c01ef974b2b905a 100644 --- a/src/test/java/org/olat/restapi/UserAuthenticationMgmtTest.java +++ b/src/test/java/org/olat/restapi/UserAuthenticationMgmtTest.java @@ -131,8 +131,7 @@ public class UserAuthenticationMgmtTest extends OlatJerseyTestCase { HttpResponse response = conn.execute(method); assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201); - InputStream body = response.getEntity().getContent(); - AuthenticationVO savedAuth = parse(body, AuthenticationVO.class); + AuthenticationVO savedAuth = conn.parse(response, AuthenticationVO.class); Authentication refAuth = baseSecurity.findAuthentication(adminIdent, "REST-API"); diff --git a/src/test/java/org/olat/restapi/UserMgmtTest.java b/src/test/java/org/olat/restapi/UserMgmtTest.java index 2fb1f3a528bc92dac59740c0c215d8c0af85b34b..8eb18b8435621005e08e49377cbe7ccbc0521711 100644 --- a/src/test/java/org/olat/restapi/UserMgmtTest.java +++ b/src/test/java/org/olat/restapi/UserMgmtTest.java @@ -141,6 +141,7 @@ public class UserMgmtTest extends OlatJerseyTestCase { //create identities owner1 = JunitTestHelper.createAndPersistIdentityAsUser("user-rest-zero"); + assertNotNull(owner1); id1 = JunitTestHelper.createAndPersistIdentityAsUser("user-rest-one-" + UUID.randomUUID().toString().replace("-", "")); id2 = JunitTestHelper.createAndPersistIdentityAsUser("user-rest-two"); DBFactory.getInstance().intermediateCommit(); @@ -371,9 +372,7 @@ public class UserMgmtTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - - UserVO vo = parse(body, UserVO.class); + UserVO vo = conn.parse(response, UserVO.class); assertNotNull(vo); assertEquals(vo.getKey(), id1.getKey()); @@ -390,9 +389,7 @@ public class UserMgmtTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - - UserVO vo = parse(body, UserVO.class); + UserVO vo = conn.parse(response, UserVO.class); assertNotNull(vo); assertEquals(vo.getKey(), id2.getKey()); @@ -460,10 +457,7 @@ public class UserMgmtTest extends OlatJerseyTestCase { HttpResponse response = conn.execute(method); assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201); - InputStream body = response.getEntity().getContent(); - - UserVO savedVo = parse(body, UserVO.class); - + UserVO savedVo = conn.parse(response, UserVO.class); Identity savedIdent = BaseSecurityManager.getInstance().findIdentityByName(username); assertNotNull(savedVo); @@ -501,10 +495,7 @@ public class UserMgmtTest extends OlatJerseyTestCase { HttpResponse response = conn.execute(method); assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201); - InputStream body = response.getEntity().getContent(); - - UserVO savedVo = parse(body, UserVO.class); - + UserVO savedVo = conn.parse(response, UserVO.class); Identity savedIdent = BaseSecurityManager.getInstance().findIdentityByName(username); assertNotNull(savedVo); @@ -574,8 +565,7 @@ public class UserMgmtTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - ForumVOes forums = parse(body, ForumVOes.class); + ForumVOes forums = conn.parse(response, ForumVOes.class); assertNotNull(forums); assertNotNull(forums.getForums()); @@ -610,8 +600,7 @@ public class UserMgmtTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - MessageVOes threads = parse(body, MessageVOes.class); + MessageVOes threads = conn.parse(response, MessageVOes.class); assertNotNull(threads); assertNotNull(threads.getMessages()); @@ -629,8 +618,7 @@ public class UserMgmtTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - MessageVOes threads = parse(body, MessageVOes.class); + MessageVOes threads = conn.parse(response, MessageVOes.class); assertNotNull(threads); assertNotNull(threads.getMessages()); @@ -646,8 +634,7 @@ public class UserMgmtTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON, true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = response.getEntity().getContent(); - FolderVOes folders = parse(body, FolderVOes.class); + FolderVOes folders = conn.parse(response, FolderVOes.class); assertNotNull(folders); assertNotNull(folders.getFolders()); @@ -801,9 +788,7 @@ public class UserMgmtTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - - InputStream body = response.getEntity().getContent(); - GroupVOes groups = parse(body, GroupVOes.class); + GroupVOes groups = conn.parse(response, GroupVOes.class); assertNotNull(groups); assertNotNull(groups.getGroups()); @@ -822,9 +807,7 @@ public class UserMgmtTest extends OlatJerseyTestCase { HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); - - InputStream body = response.getEntity().getContent(); - GroupInfoVOes groups = parse(body, GroupInfoVOes.class); + GroupInfoVOes groups = conn.parse(response, GroupInfoVOes.class); assertNotNull(groups); assertNotNull(groups.getGroups()); @@ -880,8 +863,7 @@ public class UserMgmtTest extends OlatJerseyTestCase { HttpGet getMethod2 = conn.createGet(getRequest2.build(), MediaType.APPLICATION_JSON, true); HttpResponse getCode2 = conn.execute(getMethod2); assertEquals(200, getCode2.getStatusLine().getStatusCode()); - InputStream in2 = getCode2.getEntity().getContent(); - UserVO userVo = parse(in2, UserVO.class); + UserVO userVo = conn.parse(getCode2, UserVO.class); assertNotNull(userVo); assertNotNull(userVo.getPortrait()); byte[] datas = Base64.decodeBase64(userVo.getPortrait().getBytes()); diff --git a/src/test/java/org/olat/test/AllTestsJunit4.java b/src/test/java/org/olat/test/AllTestsJunit4.java index 4f39bba58208de521c66712e3818358e8967e49f..ce49e885bb51db62f05123fcb5439b8aca28c136 100644 --- a/src/test/java/org/olat/test/AllTestsJunit4.java +++ b/src/test/java/org/olat/test/AllTestsJunit4.java @@ -74,9 +74,9 @@ import org.junit.runners.Suite; org.olat.commons.coordinate.cluster.lock.LockTest.class,//ok org.olat.commons.coordinate.CoordinatorTest.class,//ok org.olat.admin.user.delete.service.UserDeletionManagerTest.class,//ok - org.olat.group.BusinessGroupTest.class,//fail - org.olat.group.BGAreaManagerTest.class,//ok - org.olat.group.BusinessGroupManagerImplTest.class,//ok + org.olat.group.test.BGRightManagerTest.class,//fail + org.olat.group.test.BGAreaManagerTest.class,//ok + org.olat.group.test.BusinessGroupServiceImplTest.class,//ok org.olat.resource.lock.pessimistic.PLockTest.class,//ok org.olat.resource.references.ReferenceManagerTest.class,//ok org.olat.resource.OLATResourceManagerTest.class,//ok diff --git a/src/test/java/org/olat/test/OlatJerseyTestCase.java b/src/test/java/org/olat/test/OlatJerseyTestCase.java index 7f0ab2940f0e7420b8a6e32ac61b58e448486123..5586d39103b194ddfee223254d171178c4cc15a4 100644 --- a/src/test/java/org/olat/test/OlatJerseyTestCase.java +++ b/src/test/java/org/olat/test/OlatJerseyTestCase.java @@ -131,28 +131,6 @@ public abstract class OlatJerseyTestCase extends OlatTestCase { log.error("Cannot start the Grizzly Web Container"); } } - - protected <T> T parse(String body, Class<T> cl) { - try { - ObjectMapper mapper = new ObjectMapper(jsonFactory); - T obj = mapper.readValue(body, cl); - return obj; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - protected <T> T parse(InputStream body, Class<T> cl) { - try { - ObjectMapper mapper = new ObjectMapper(jsonFactory); - T obj = mapper.readValue(body, cl); - return obj; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } protected List<ErrorVO> parseErrorArray(InputStream body) { try {