Search in sources :

Example 31 with PropertyManager

use of org.olat.properties.PropertyManager 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();
}
Also used : INode(org.olat.core.util.nodes.INode) Visitor(org.olat.core.util.tree.Visitor) CourseTreeVisitor(org.olat.course.run.userview.CourseTreeVisitor) HashMap(java.util.HashMap) VisibleTreeFilter(org.olat.course.run.userview.VisibleTreeFilter) PropertyManager(org.olat.properties.PropertyManager) ArrayList(java.util.ArrayList) ICourse(org.olat.course.ICourse) FOCourseNode(org.olat.course.nodes.FOCourseNode) Subscriber(org.olat.core.commons.services.notifications.Subscriber) ArrayList(java.util.ArrayList) List(java.util.List) RestSecurityHelper.getIdentity(org.olat.restapi.security.RestSecurityHelper.getIdentity) Identity(org.olat.core.id.Identity) IdentityEnvironment(org.olat.core.id.IdentityEnvironment) Property(org.olat.properties.Property) HashSet(java.util.HashSet) BusinessGroup(org.olat.group.BusinessGroup) CourseTreeVisitor(org.olat.course.run.userview.CourseTreeVisitor) RestSecurityHelper.getRoles(org.olat.restapi.security.RestSecurityHelper.getRoles) Roles(org.olat.core.id.Roles) SearchBusinessGroupParams(org.olat.group.model.SearchBusinessGroupParams) BusinessGroupService(org.olat.group.BusinessGroupService) NotificationsManager(org.olat.core.commons.services.notifications.NotificationsManager) Collection(java.util.Collection) HashMap(java.util.HashMap) Map(java.util.Map) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 32 with PropertyManager

use of org.olat.properties.PropertyManager in project OpenOLAT by OpenOLAT.

the class AbstractStatisticUpdateManagerTest method setLastUpdate.

protected void setLastUpdate(Calendar ref, int dayInThePast) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, ref.get(Calendar.YEAR));
    cal.set(Calendar.MONTH, ref.get(Calendar.MONTH));
    cal.set(Calendar.DATE, 1);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.add(Calendar.DATE, -dayInThePast);
    long lastUpdated = cal.getTimeInMillis();
    PropertyManager pm = PropertyManager.getInstance();
    Property p = pm.findProperty(null, null, null, "STATISTICS_PROPERTIES", "LAST_UPDATED");
    if (p == null) {
        p = pm.createPropertyInstance(null, null, null, "STATISTICS_PROPERTIES", "LAST_UPDATED", null, lastUpdated, null, null);
    } else {
        p.setLongValue(lastUpdated);
    }
    pm.saveProperty(p);
}
Also used : PropertyManager(org.olat.properties.PropertyManager) Calendar(java.util.Calendar) Property(org.olat.properties.Property)

Example 33 with PropertyManager

use of org.olat.properties.PropertyManager in project OpenOLAT by OpenOLAT.

the class DBTest method testRollback.

@Test
public void testRollback() {
    String propertyKey = "testRollback-1";
    String testValue = "testRollback-1";
    try {
        PropertyManager pm = PropertyManager.getInstance();
        Property p1 = pm.createPropertyInstance(null, null, null, null, propertyKey, null, null, testValue, null);
        pm.saveProperty(p1);
        String testValue2 = "testRollback-2";
        // name is null => generated DB error => rollback
        Property p2 = pm.createPropertyInstance(null, null, null, null, null, null, null, testValue2, null);
        pm.saveProperty(p2);
        dbInstance.commit();
        fail("Should generate error for rollback.");
    } catch (Exception ex) {
        dbInstance.closeSession();
    }
    // check if p1 is rollbacked
    PropertyManager pm = PropertyManager.getInstance();
    Property p = pm.findProperty(null, null, null, null, propertyKey);
    assertNull("Property.save is NOT rollbacked", p);
}
Also used : PropertyManager(org.olat.properties.PropertyManager) Property(org.olat.properties.Property) DBRuntimeException(org.olat.core.logging.DBRuntimeException) Test(org.junit.Test)

Example 34 with PropertyManager

use of org.olat.properties.PropertyManager in project OpenOLAT by OpenOLAT.

the class DBTest method testDbPerf.

@Test
public void testDbPerf() {
    int loops = 1000;
    long timeWithoutTransction = 0;
    log.info("start testDbPerf with loops=" + loops);
    try {
        long startTime = System.currentTimeMillis();
        for (int loopCounter = 0; loopCounter < loops; loopCounter++) {
            String propertyKey = "testDbPerfKey-" + loopCounter;
            PropertyManager pm = PropertyManager.getInstance();
            String testValue = "testDbPerfValue-" + loopCounter;
            Property p = pm.createPropertyInstance(null, null, null, null, propertyKey, null, null, testValue, null);
            pm.saveProperty(p);
            // forget session cache etc.
            dbInstance.closeSession();
            pm.deleteProperty(p);
        }
        long endTime = System.currentTimeMillis();
        timeWithoutTransction = endTime - startTime;
        log.info("testDbPerf without transaction takes :" + timeWithoutTransction + "ms");
    } catch (Exception ex) {
        fail("Exception in testDbPerf without transaction ex=" + ex);
    }
    try {
        long startTime = System.currentTimeMillis();
        for (int loopCounter = 0; loopCounter < loops; loopCounter++) {
            String propertyKey = "testDbPerfKey-" + loopCounter;
            PropertyManager pm = PropertyManager.getInstance();
            String testValue = "testDbPerfValue-" + loopCounter;
            Property p = pm.createPropertyInstance(null, null, null, null, propertyKey, null, null, testValue, null);
            pm.saveProperty(p);
            // forget session cache etc.
            dbInstance.closeSession();
            pm.deleteProperty(p);
        }
        long endTime = System.currentTimeMillis();
        long timeWithTransction = endTime - startTime;
        log.info("testDbPerf with transaction takes :" + timeWithTransction + "ms");
        log.info("testDbPerf diff between transaction and without transaction :" + (timeWithTransction - timeWithoutTransction) + "ms");
    } catch (Exception ex) {
        fail("Exception in testDbPerf with transaction ex=" + ex);
    }
}
Also used : PropertyManager(org.olat.properties.PropertyManager) Property(org.olat.properties.Property) DBRuntimeException(org.olat.core.logging.DBRuntimeException) Test(org.junit.Test)

Example 35 with PropertyManager

use of org.olat.properties.PropertyManager in project OpenOLAT by OpenOLAT.

the class DBPersistentLockManager method releasePersistentLock.

/**
 * @see org.olat.core.util.locks.PersistentLockManager#releasePersistentLock(org.olat.core.util.locks.LockEntry)
 */
@Override
public void releasePersistentLock(LockResult le) {
    // synchronisation is solved in the LockManager
    String derivedLockString = ((LockResultImpl) le).getLockEntry().getKey();
    PropertyManager pm = PropertyManager.getInstance();
    Property p = pm.findProperty(null, null, null, CATEGORY_PERSISTENTLOCK, derivedLockString);
    if (p == null)
        throw new AssertException("could not release lock: no lock in db, " + derivedLockString);
    Identity ident = le.getOwner();
    Long ownerKey = p.getLongValue();
    if (!ownerKey.equals(ident.getKey()))
        throw new AssertException("user " + ident.getName() + " cannot release lock belonging to user with key " + ownerKey + " on resourcestring " + derivedLockString);
    pm.deleteProperty(p);
}
Also used : AssertException(org.olat.core.logging.AssertException) PropertyManager(org.olat.properties.PropertyManager) Identity(org.olat.core.id.Identity) Property(org.olat.properties.Property)

Aggregations

PropertyManager (org.olat.properties.PropertyManager)50 Property (org.olat.properties.Property)48 Test (org.junit.Test)10 Identity (org.olat.core.id.Identity)8 DBRuntimeException (org.olat.core.logging.DBRuntimeException)8 OLATRuntimeException (org.olat.core.logging.OLATRuntimeException)6 ArrayList (java.util.ArrayList)4 GET (javax.ws.rs.GET)4 Produces (javax.ws.rs.Produces)4 UserSession (org.olat.core.util.UserSession)4 NarrowedPropertyManager (org.olat.properties.NarrowedPropertyManager)4 OLATResourceable (org.olat.core.id.OLATResourceable)3 SyncerExecutor (org.olat.core.util.coordinate.SyncerExecutor)3 File (java.io.File)2 IOException (java.io.IOException)2 Calendar (java.util.Calendar)2 Collection (java.util.Collection)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 List (java.util.List)2