use of org.olat.core.util.tree.Visitor in project openolat by klemens.
the class MyForumsTest method myForums.
/**
* Test retrieve the forum which the user subscribe in a course.
* @throws IOException
* @throws URISyntaxException
*/
@Test
public void myForums() throws IOException, URISyntaxException {
URL courseWithForumsUrl = MyForumsTest.class.getResource("myCourseWS.zip");
Assert.assertNotNull(courseWithForumsUrl);
File courseWithForums = new File(courseWithForumsUrl.toURI());
String softKey = UUID.randomUUID().toString().replace("_", "");
RepositoryEntry myCourseRe = CourseFactory.deployCourseFromZIP(courseWithForums, softKey, 4);
Assert.assertNotNull(myCourseRe);
ICourse myCourse = CourseFactory.loadCourse(myCourseRe);
final Identity id = JunitTestHelper.createAndPersistIdentityAsUser("my-" + UUID.randomUUID().toString());
dbInstance.commitAndCloseSession();
// load my forums
RestConnection conn = new RestConnection();
assertTrue(conn.login(id.getName(), "A6B7C8"));
// subscribed to nothing
URI uri = UriBuilder.fromUri(getContextURI()).path("users").path(id.getKey().toString()).path("forums").build();
HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
InputStream body = response.getEntity().getContent();
ForumVOes forums = conn.parse(body, ForumVOes.class);
Assert.assertNotNull(forums);
Assert.assertNotNull(forums.getForums());
Assert.assertEquals(0, forums.getForums().length);
// subscribe to the forum
IdentityEnvironment ienv = new IdentityEnvironment(id, new Roles(false, false, false, false, false, false, false));
new CourseTreeVisitor(myCourse, ienv).visit(new Visitor() {
@Override
public void visit(INode node) {
if (node instanceof FOCourseNode) {
FOCourseNode forumNode = (FOCourseNode) node;
Forum forum = forumNode.loadOrCreateForum(myCourse.getCourseEnvironment());
String businessPath = "[RepositoryEntry:" + myCourseRe.getKey() + "][CourseNode:" + forumNode.getIdent() + "]";
SubscriptionContext forumSubContext = new SubscriptionContext("CourseModule", myCourse.getResourceableId(), forumNode.getIdent());
PublisherData forumPdata = new PublisherData(OresHelper.calculateTypeName(Forum.class), forum.getKey().toString(), businessPath);
NotificationsManager.getInstance().subscribe(id, forumSubContext, forumPdata);
}
}
}, new VisibleTreeFilter());
dbInstance.commitAndCloseSession();
// retrieve my forums
HttpGet method2 = conn.createGet(uri, MediaType.APPLICATION_JSON, true);
HttpResponse response2 = conn.execute(method2);
assertEquals(200, response2.getStatusLine().getStatusCode());
InputStream body2 = response2.getEntity().getContent();
ForumVOes forums2 = conn.parse(body2, ForumVOes.class);
Assert.assertNotNull(forums2);
Assert.assertNotNull(forums2.getForums());
Assert.assertEquals(1, forums2.getForums().length);
}
use of org.olat.core.util.tree.Visitor in project openolat by klemens.
the class CoursesInfosWebService method collect.
private CourseInfoVO collect(final Identity identity, final Roles roles, final RepositoryEntry entry, final Set<Long> forumNotified, final Map<Long, Set<String>> courseNotified) {
CourseInfoVO info = new CourseInfoVO();
info.setRepoEntryKey(entry.getKey());
info.setSoftKey(entry.getSoftkey());
info.setDisplayName(entry.getDisplayname());
ACService acManager = CoreSpringFactory.getImpl(ACService.class);
AccessResult result = acManager.isAccessible(entry, identity, false);
if (result.isAccessible()) {
try {
final ICourse course = CourseFactory.loadCourse(entry);
final List<FolderVO> folders = new ArrayList<FolderVO>();
final List<ForumVO> forums = new ArrayList<ForumVO>();
final IdentityEnvironment ienv = new IdentityEnvironment(identity, roles);
new CourseTreeVisitor(course, ienv).visit(new Visitor() {
@Override
public void visit(INode node) {
if (node instanceof BCCourseNode) {
BCCourseNode bcNode = (BCCourseNode) node;
folders.add(BCWebService.createFolderVO(ienv, course, bcNode, courseNotified.get(course.getResourceableId())));
} else if (node instanceof FOCourseNode) {
FOCourseNode forumNode = (FOCourseNode) node;
forums.add(ForumCourseNodeWebService.createForumVO(course, forumNode, forumNotified));
}
}
}, new VisibleTreeFilter());
info.setKey(course.getResourceableId());
info.setTitle(course.getCourseTitle());
info.setFolders(folders.toArray(new FolderVO[folders.size()]));
info.setForums(forums.toArray(new ForumVO[forums.size()]));
} catch (Exception e) {
log.error("", e);
}
}
return info;
}
use of org.olat.core.util.tree.Visitor in project openolat by klemens.
the class CPSelectPrintPagesController method getSelectedNodeIdentifiers.
public List<String> getSelectedNodeIdentifiers() {
final Set<String> selectedKeys = cpTree.getSelectedKeys();
final List<String> orderedIdentifiers = new ArrayList<>();
TreeVisitor visitor = new TreeVisitor(new Visitor() {
@Override
public void visit(INode node) {
if (selectedKeys.contains(node.getIdent())) {
orderedIdentifiers.add(node.getIdent());
}
}
}, ctm.getRootNode(), false);
visitor.visitAll();
return orderedIdentifiers;
}
use of org.olat.core.util.tree.Visitor in project openolat by klemens.
the class NodeExportVisitor method exportToFilesystem.
/**
* @see org.olat.course.ICourse#exportToFilesystem(java.io.File)
* <p>
* See OLAT-5368: Course Export can take longer than say 2min.
* <p>
*/
@Override
public void exportToFilesystem(OLATResource originalCourseResource, File exportDirectory, boolean runtimeDatas, boolean backwardsCompatible) {
long s = System.currentTimeMillis();
log.info("exportToFilesystem: exporting course " + this + " to " + exportDirectory + "...");
File fCourseBase = getCourseBaseContainer().getBasefile();
// make the folder structure
File fExportedDataDir = new File(exportDirectory, EXPORTED_DATA_FOLDERNAME);
fExportedDataDir.mkdirs();
// export course config
FileUtils.copyFileToDir(new File(fCourseBase, CourseConfigManager.COURSECONFIG_XML), exportDirectory, "course export courseconfig");
// export business groups
CourseEnvironmentMapper envMapper = getCourseEnvironment().getCourseGroupManager().getBusinessGroupEnvironment();
if (backwardsCompatible) {
// prevents duplicate names
envMapper.avoidDuplicateNames();
}
getCourseEnvironment().getCourseGroupManager().exportCourseBusinessGroups(fExportedDataDir, envMapper, runtimeDatas, backwardsCompatible);
if (backwardsCompatible) {
XStream xstream = CourseXStreamAliases.getReadCourseXStream();
Structure exportedStructure = (Structure) XStreamHelper.readObject(xstream, new File(fCourseBase, RUNSTRUCTURE_XML));
visit(new NodePostExportVisitor(envMapper, backwardsCompatible), exportedStructure.getRootNode());
XStreamHelper.writeObject(xstream, new File(exportDirectory, RUNSTRUCTURE_XML), exportedStructure);
CourseEditorTreeModel exportedEditorModel = (CourseEditorTreeModel) XStreamHelper.readObject(xstream, new File(fCourseBase, EDITORTREEMODEL_XML));
visit(new NodePostExportVisitor(envMapper, backwardsCompatible), exportedEditorModel.getRootNode());
XStreamHelper.writeObject(xstream, new File(exportDirectory, EDITORTREEMODEL_XML), exportedEditorModel);
} else {
// export editor structure
FileUtils.copyFileToDir(new File(fCourseBase, EDITORTREEMODEL_XML), exportDirectory, "course export exitortreemodel");
// export run structure
FileUtils.copyFileToDir(new File(fCourseBase, RUNSTRUCTURE_XML), exportDirectory, "course export runstructure");
}
// export layout and media folder
FileUtils.copyDirToDir(new File(fCourseBase, "layout"), exportDirectory, "course export layout folder");
FileUtils.copyDirToDir(new File(fCourseBase, "media"), exportDirectory, "course export media folder");
// export course folder
FileUtils.copyDirToDir(getIsolatedCourseBaseFolder(), exportDirectory, "course export folder");
// export any node data
log.info("exportToFilesystem: exporting course " + this + ": exporting all nodes...");
Visitor visitor = new NodeExportVisitor(fExportedDataDir, this);
TreeVisitor tv = new TreeVisitor(visitor, getEditorTreeModel().getRootNode(), true);
tv.visitAll();
log.info("exportToFilesystem: exporting course " + this + ": exporting all nodes...done.");
// OLAT-5368: do intermediate commit to avoid transaction timeout
// discussion intermediatecommit vs increased transaction timeout:
// pro intermediatecommit: not much
// pro increased transaction timeout: would fix OLAT-5368 but only move the problem
// @TODO OLAT-2597: real solution is a long-running background-task concept...
DBFactory.getInstance().intermediateCommit();
// export shared folder
CourseConfig config = getCourseConfig();
if (config.hasCustomSharedFolder()) {
log.info("exportToFilesystem: exporting course " + this + ": shared folder...");
if (!SharedFolderManager.getInstance().exportSharedFolder(config.getSharedFolderSoftkey(), fExportedDataDir)) {
// export failed, delete reference to shared folder in the course config
log.info("exportToFilesystem: exporting course " + this + ": export of shared folder failed.");
config.setSharedFolderSoftkey(CourseConfig.VALUE_EMPTY_SHAREDFOLDER_SOFTKEY);
CourseConfigManagerImpl.getInstance().saveConfigTo(this, config);
}
log.info("exportToFilesystem: exporting course " + this + ": shared folder...done.");
}
// OLAT-5368: do intermediate commit to avoid transaction timeout
// discussion intermediatecommit vs increased transaction timeout:
// pro intermediatecommit: not much
// pro increased transaction timeout: would fix OLAT-5368 but only move the problem
// @TODO OLAT-2597: real solution is a long-running background-task concept...
DBFactory.getInstance().intermediateCommit();
// export glossary
if (config.hasGlossary()) {
log.info("exportToFilesystem: exporting course " + this + ": glossary...");
if (!GlossaryManager.getInstance().exportGlossary(config.getGlossarySoftKey(), fExportedDataDir)) {
// export failed, delete reference to glossary in the course config
log.info("exportToFilesystem: exporting course " + this + ": export of glossary failed.");
config.setGlossarySoftKey(null);
CourseConfigManagerImpl.getInstance().saveConfigTo(this, config);
}
log.info("exportToFilesystem: exporting course " + this + ": glossary...done.");
}
// OLAT-5368: do intermediate commit to avoid transaction timeout
// discussion intermediatecommit vs increased transaction timeout:
// pro intermediatecommit: not much
// pro increased transaction timeout: would fix OLAT-5368 but only move the problem
// @TODO OLAT-2597: real solution is a long-running background-task concept...
DBFactory.getInstance().intermediateCommit();
log.info("exportToFilesystem: exporting course " + this + ": configuration and repo data...");
// export configuration file
FileUtils.copyFileToDir(new File(fCourseBase, CourseConfigManager.COURSECONFIG_XML), exportDirectory, "course export configuration and repo info");
// export repo metadata
RepositoryManager rm = RepositoryManager.getInstance();
RepositoryEntry myRE = rm.lookupRepositoryEntry(this, true);
RepositoryEntryImportExport importExport = new RepositoryEntryImportExport(myRE, fExportedDataDir);
importExport.exportDoExportProperties();
// OLAT-5368: do intermediate commit to avoid transaction timeout
// discussion intermediatecommit vs increased transaction timeout:
// pro intermediatecommit: not much
// pro increased transaction timeout: would fix OLAT-5368 but only move the problem
// @TODO OLAT-2597: real solution is a long-running background-task concept...
DBFactory.getInstance().intermediateCommit();
// export reminders
CoreSpringFactory.getImpl(ReminderService.class).exportReminders(myRE, fExportedDataDir);
log.info("exportToFilesystem: exporting course " + this + " to " + exportDirectory + " done.");
log.info("finished export course '" + getCourseTitle() + "' in t=" + Long.toString(System.currentTimeMillis() - s));
}
use of org.olat.core.util.tree.Visitor in project openolat by klemens.
the class MyForumsWebService method getForums.
/**
* Retrieves a list of forums on a user base. All forums of groups
* where the user is participant/tutor + all forums in course where
* the user is a participant (owner, tutor or participant)
* @response.representation.200.qname {http://www.example.com}forumVO
* @response.representation.200.mediaType application/xml, application/json
* @response.representation.200.doc The forums
* @response.representation.200.example {@link org.olat.modules.fo.restapi.Examples#SAMPLE_FORUMVO}
* @response.representation.401.doc The roles of the authenticated user are not sufficient
* @param identityKey The key of the user (IdentityImpl)
* @param httpRequest The HTTP request
* @return The forums
*/
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getForums(@PathParam("identityKey") Long identityKey, @Context HttpServletRequest httpRequest) {
Roles roles;
Identity retrievedUser = getIdentity(httpRequest);
if (retrievedUser == null) {
return Response.serverError().status(Status.UNAUTHORIZED).build();
} else if (!identityKey.equals(retrievedUser.getKey())) {
if (isAdmin(httpRequest)) {
retrievedUser = BaseSecurityManager.getInstance().loadIdentityByKey(identityKey);
roles = BaseSecurityManager.getInstance().getRoles(retrievedUser);
} else {
return Response.serverError().status(Status.UNAUTHORIZED).build();
}
} else {
roles = getRoles(httpRequest);
}
Map<Long, Long> groupNotified = new HashMap<Long, Long>();
Map<Long, Collection<Long>> courseNotified = new HashMap<Long, Collection<Long>>();
final Set<Long> subscriptions = new HashSet<Long>();
NotificationsManager man = NotificationsManager.getInstance();
{
// collect subscriptions
List<String> notiTypes = Collections.singletonList("Forum");
List<Subscriber> subs = man.getSubscribers(retrievedUser, notiTypes);
for (Subscriber sub : subs) {
String resName = sub.getPublisher().getResName();
Long forumKey = Long.parseLong(sub.getPublisher().getData());
subscriptions.add(forumKey);
if ("BusinessGroup".equals(resName)) {
Long groupKey = sub.getPublisher().getResId();
groupNotified.put(groupKey, forumKey);
} else if ("CourseModule".equals(resName)) {
Long courseKey = sub.getPublisher().getResId();
if (!courseNotified.containsKey(courseKey)) {
courseNotified.put(courseKey, new ArrayList<Long>());
}
courseNotified.get(courseKey).add(forumKey);
}
}
}
final List<ForumVO> forumVOs = new ArrayList<ForumVO>();
final IdentityEnvironment ienv = new IdentityEnvironment(retrievedUser, roles);
for (Map.Entry<Long, Collection<Long>> e : courseNotified.entrySet()) {
final Long courseKey = e.getKey();
final Collection<Long> forumKeys = e.getValue();
final ICourse course = CourseFactory.loadCourse(courseKey);
new CourseTreeVisitor(course, ienv).visit(new Visitor() {
@Override
public void visit(INode node) {
if (node instanceof FOCourseNode) {
FOCourseNode forumNode = (FOCourseNode) node;
ForumVO forumVo = ForumCourseNodeWebService.createForumVO(course, forumNode, subscriptions);
if (forumKeys.contains(forumVo.getForumKey())) {
forumVOs.add(forumVo);
}
}
}
}, new VisibleTreeFilter());
}
/*
RepositoryManager rm = RepositoryManager.getInstance();
ACService acManager = CoreSpringFactory.getImpl(ACService.class);
SearchRepositoryEntryParameters repoParams = new SearchRepositoryEntryParameters(retrievedUser, roles, "CourseModule");
repoParams.setOnlyExplicitMember(true);
List<RepositoryEntry> entries = rm.genericANDQueryWithRolesRestriction(repoParams, 0, -1, true);
for(RepositoryEntry entry:entries) {
AccessResult result = acManager.isAccessible(entry, retrievedUser, false);
if(result.isAccessible()) {
try {
final ICourse course = CourseFactory.loadCourse(entry.getOlatResource());
final IdentityEnvironment ienv = new IdentityEnvironment(retrievedUser, roles);
new CourseTreeVisitor(course, ienv).visit(new Visitor() {
@Override
public void visit(INode node) {
if(node instanceof FOCourseNode) {
FOCourseNode forumNode = (FOCourseNode)node;
ForumVO forumVo = ForumCourseNodeWebService.createForumVO(course, forumNode, subscriptions);
forumVOs.add(forumVo);
}
}
});
} catch (Exception e) {
log.error("", e);
}
}
}*/
// start found forums in groups
BusinessGroupService bgs = CoreSpringFactory.getImpl(BusinessGroupService.class);
SearchBusinessGroupParams params = new SearchBusinessGroupParams(retrievedUser, true, true);
params.addTools(CollaborationTools.TOOL_FORUM);
List<BusinessGroup> groups = bgs.findBusinessGroups(params, null, 0, -1);
// list forum keys
List<Long> groupIds = new ArrayList<Long>();
Map<Long, BusinessGroup> groupsMap = new HashMap<Long, BusinessGroup>();
for (BusinessGroup group : groups) {
if (groupNotified.containsKey(group.getKey())) {
ForumVO forumVo = new ForumVO();
forumVo.setName(group.getName());
forumVo.setGroupKey(group.getKey());
forumVo.setForumKey(groupNotified.get(group.getKey()));
forumVo.setSubscribed(true);
forumVOs.add(forumVo);
groupIds.remove(group.getKey());
} else {
groupIds.add(group.getKey());
groupsMap.put(group.getKey(), group);
}
}
PropertyManager pm = PropertyManager.getInstance();
List<Property> forumProperties = pm.findProperties(OresHelper.calculateTypeName(BusinessGroup.class), groupIds, PROP_CAT_BG_COLLABTOOLS, KEY_FORUM);
for (Property prop : forumProperties) {
Long forumKey = prop.getLongValue();
if (forumKey != null && groupsMap.containsKey(prop.getResourceTypeId())) {
BusinessGroup group = groupsMap.get(prop.getResourceTypeId());
ForumVO forumVo = new ForumVO();
forumVo.setName(group.getName());
forumVo.setGroupKey(group.getKey());
forumVo.setForumKey(prop.getLongValue());
forumVo.setSubscribed(false);
forumVOs.add(forumVo);
}
}
ForumVOes voes = new ForumVOes();
voes.setForums(forumVOs.toArray(new ForumVO[forumVOs.size()]));
voes.setTotalCount(forumVOs.size());
return Response.ok(voes).build();
}
Aggregations