private UserStatisticsVO getUserStatistics() {
    UserStatisticsVO stats = new UserStatisticsVO();

    BaseSecurity securityManager = CoreSpringFactory.getImpl(BaseSecurity.class);
    long countUsers =
        securityManager.countIdentitiesByPowerSearch(
            null, null, false, null, null, null, null, null, null, null, null);
    stats.setTotalUserCount(countUsers);

    BusinessGroupService bgs = CoreSpringFactory.getImpl(BusinessGroupService.class);
    long countGroups = bgs.countBusinessGroups(null, null);
    stats.setTotalGroupCount(countGroups);
    return stats;
  }
Example #2
0
  /** testGetAllResourceTypeNames */
  @Test
  public void testGetAllResourceTypeNames() {
    // create resource, identity and group
    OLATResource ores = JunitTestHelper.createRandomResource();
    Identity identity =
        JunitTestHelper.createAndPersistIdentityAsUser("prop-3-" + UUID.randomUUID().toString());
    BusinessGroup group =
        businessGroupService.createBusinessGroup(
            identity, "a buddygroup", "a desc", -1, -1, false, false, null);
    dbInstance.commitAndCloseSession();

    // create a property
    Property p =
        pm.createPropertyInstance(
            identity,
            group,
            ores,
            "catall",
            "TestProperty",
            new Float(1.1),
            new Long(123456),
            "stringValue",
            "textValue");
    pm.saveProperty(p);
    dbInstance.commitAndCloseSession();

    Assert.assertNotNull(p.getResourceTypeName());
    List<String> resTypeNames = pm.getAllResourceTypeNames();
    assertTrue(resTypeNames.contains(ores.getResourceableTypeName()));
  }
Example #3
0
  /**
   * Retrieves the groups where the enrollment happens
   *
   * @response.representation.200.qname {http://www.example.com}groupVO
   * @response.representation.200.mediaType application/xml, application/json
   * @response.representation.200.doc The groups
   * @response.representation.200.example {@link
   *     org.olat.restapi.support.vo.Examples#SAMPLE_GROUPVO}
   * @response.representation.401.doc The roles of the authenticated user are not sufficient
   * @response.representation.404.doc The course or course node not found
   * @param nodeId The node's id
   * @param httpRequest The HTTP request
   * @return An array of groups
   */
  @GET
  @Path("{nodeId}/groups")
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  public Response getGroups(
      @PathParam("courseId") Long courseId,
      @PathParam("nodeId") String nodeId,
      @Context HttpServletRequest httpRequest) {

    if (!isAuthor(httpRequest)) {
      return Response.serverError().status(Status.UNAUTHORIZED).build();
    }
    ICourse course = CoursesWebService.loadCourse(courseId);
    if (course == null) {
      return Response.serverError().status(Status.NOT_FOUND).build();
    } else if (!isAuthorEditor(course, httpRequest)) {
      return Response.serverError().status(Status.UNAUTHORIZED).build();
    }

    BusinessGroupService bgs = CoreSpringFactory.getImpl(BusinessGroupService.class);

    CourseNode node = getParentNode(course, nodeId);
    ModuleConfiguration config = node.getModuleConfiguration();
    String groupNames = (String) config.get(ENCourseNode.CONFIG_GROUPNAME);
    @SuppressWarnings("unchecked")
    List<Long> groupKeys = (List<Long>) config.get(ENCourseNode.CONFIG_GROUP_IDS);
    if (groupKeys == null && StringHelper.containsNonWhitespace(groupNames)) {
      groupKeys =
          bgs.toGroupKeys(
              groupNames, course.getCourseEnvironment().getCourseGroupManager().getCourseEntry());
    }

    if (groupKeys == null || groupKeys.isEmpty()) {
      return Response.ok(new GroupVO[0]).build();
    }

    List<GroupVO> voes = new ArrayList<GroupVO>();
    List<BusinessGroup> groups = bgs.loadBusinessGroups(groupKeys);
    for (BusinessGroup group : groups) {
      voes.add(get(group));
    }
    GroupVO[] voArr = new GroupVO[voes.size()];
    voes.toArray(voArr);
    return Response.ok(voArr).build();
  }
Example #4
0
  @Test
  public void testFindProperties() {
    // create identities, group and resource
    OLATResource res = JunitTestHelper.createRandomResource();
    Identity id1 =
        JunitTestHelper.createAndPersistIdentityAsUser("prop-8-" + UUID.randomUUID().toString());
    Identity id2 =
        JunitTestHelper.createAndPersistIdentityAsUser("prop-9-" + UUID.randomUUID().toString());
    BusinessGroup group =
        businessGroupService.createBusinessGroup(
            id1, "a buddygroup", "a desc", -1, -1, false, false, null);
    dbInstance.commitAndCloseSession();

    String category = "cat3";
    String propertyName = "TestProperty3";
    String textValue = "textValue3";
    Property p =
        pm.createPropertyInstance(
            id1,
            group,
            res,
            category,
            propertyName,
            new Float(1.1),
            new Long(123456),
            "stringValue",
            textValue);
    pm.saveProperty(p);
    p =
        pm.createPropertyInstance(
            id2,
            group,
            res,
            category,
            propertyName,
            new Float(1.1),
            new Long(123456),
            "stringValue",
            textValue);
    pm.saveProperty(p);
    List<Property> propertyList =
        pm.findProperties(
            id1,
            group,
            res.getResourceableTypeName(),
            res.getResourceableId(),
            category,
            propertyName);
    assertEquals(1, propertyList.size());
    assertEquals(propertyName, propertyList.get(0).getName());
    assertEquals(textValue, propertyList.get(0).getTextValue());
    int deletedCount1 = pm.deleteProperties(id1, group, res, category, propertyName);
    Assert.assertEquals(1, deletedCount1);
    int deletedCount2 = pm.deleteProperties(id2, group, res, category, propertyName);
    Assert.assertEquals(1, deletedCount2);
  }
  private void appendGroupCalendars(
      Identity identity,
      List<KalendarRenderWrapper> calendars,
      Map<CalendarKey, CalendarUserConfiguration> configMap) {
    // get group calendars
    if (calendarModule.isEnableGroupCalendar()) {
      SearchBusinessGroupParams groupParams = new SearchBusinessGroupParams(identity, true, false);
      groupParams.addTools(CollaborationTools.TOOL_CALENDAR);
      List<BusinessGroup> ownerGroups =
          businessGroupService.findBusinessGroups(groupParams, null, 0, -1);
      addCalendars(ownerGroups, true, false, calendars, configMap);

      SearchBusinessGroupParams groupParams2 = new SearchBusinessGroupParams(identity, false, true);
      groupParams2.addTools(CollaborationTools.TOOL_CALENDAR);
      List<BusinessGroup> attendedGroups =
          businessGroupService.findBusinessGroups(groupParams2, null, 0, -1);
      attendedGroups.removeAll(ownerGroups);
      addCalendars(attendedGroups, false, true, calendars, configMap);
    }
  }
Example #6
0
    private List<String> getGroupNames(String groupIds) {
      List<String> groupNames = new ArrayList<String>();

      if (StringHelper.containsNonWhitespace(groupIds)) {
        String[] groupIdArr = groupIds.split(";");
        BusinessGroupService bgm = CoreSpringFactory.getImpl(BusinessGroupService.class);

        List<Long> keys = new ArrayList<Long>();
        for (String groupId : groupIdArr) {
          Long groupKey = new Long(groupId);
          keys.add(groupKey);
        }
        List<BusinessGroupShort> groupsShort = bgm.loadShortBusinessGroups(keys);
        for (BusinessGroupShort bg : groupsShort) {
          groupNames.add(bg.getName());
        }
      }

      return groupNames;
    }
  /**
   * Perform a search for the given search value in the search result providers and clear any GUI
   * errors that might be on the page
   *
   * @param searchValue
   * @param ureq
   */
  private void doSearchGroups(String searchValue, UserRequest ureq) {
    if (StringHelper.containsNonWhitespace(searchValue)) {
      SearchBusinessGroupParams param1s = new SearchBusinessGroupParams();
      param1s.setNameOrDesc(searchValue);
      List<BusinessGroup> group1s = businessGroupService.findBusinessGroups(param1s, null, 0, -1);
      filterGroups(group1s);

      SearchBusinessGroupParams param2s = new SearchBusinessGroupParams();
      param2s.setCourseTitle(searchValue);
      List<BusinessGroup> group2s = businessGroupService.findBusinessGroups(param2s, null, 0, -1);
      filterGroups(group2s);

      List<BusinessGroup> groups = new ArrayList<BusinessGroup>(group1s.size() + group2s.size());
      groups.addAll(group1s);
      groups.addAll(group2s);

      List<Long> groupKeysWithRelations = PersistenceHelper.toKeys(groups);
      List<BGRepositoryEntryRelation> resources =
          businessGroupService.findRelationToRepositoryEntries(groupKeysWithRelations, 0, -1);

      List<GroupWrapper> groupWrappers = new ArrayList<GroupWrapper>();
      for (BusinessGroup group : groups) {
        StringBuilder sb = new StringBuilder();
        for (BGRepositoryEntryRelation resource : resources) {
          if (resource.getGroupKey().equals(group.getKey())) {
            if (sb.length() > 0) sb.append(", ");
            sb.append(resource.getRepositoryEntryDisplayName());
          }
        }

        GroupWrapper wrapper = new GroupWrapper(group, sb.toString());
        wrapper.setTutor(createSelection("tutor_" + group.getKey()));
        wrapper.setParticipant(createSelection("participant_" + group.getKey()));
        groupWrappers.add(wrapper);
      }

      table.reset();
      tableDataModel.setObjects(groupWrappers);
      errorComp.clearError();
    }
  }
Example #8
0
  /** testListProperties */
  @Test
  public void testListProperties() {
    // create resource, identity and group
    OLATResource ores = JunitTestHelper.createRandomResource();
    Identity identity =
        JunitTestHelper.createAndPersistIdentityAsUser("prop-4-" + UUID.randomUUID().toString());
    BusinessGroup group =
        businessGroupService.createBusinessGroup(
            identity, "a buddygroup", "a desc", -1, -1, false, false, null);
    dbInstance.commitAndCloseSession();

    Property p =
        pm.createPropertyInstance(
            identity,
            group,
            ores,
            "cat",
            "TestProperty",
            new Float(1.1),
            new Long(123456),
            "stringValue",
            "textValue");
    pm.saveProperty(p);

    List<Property> entries =
        PropertyManager.getInstance()
            .listProperties(
                identity,
                group,
                ores.getResourceableTypeName(),
                ores.getResourceableId(),
                "cat",
                "TestProperty");
    Assert.assertNotNull(entries);
    Assert.assertEquals(1, entries.size());

    Property prop = entries.get(0);
    assertEquals(ores.getResourceableTypeName(), prop.getResourceTypeName());
    assertEquals(ores.getResourceableId(), prop.getResourceTypeId());

    int numOfEntries =
        PropertyManager.getInstance()
            .countProperties(
                identity,
                group,
                ores.getResourceableTypeName(),
                ores.getResourceableId(),
                "cat",
                "TestProperty",
                null,
                null);
    Assert.assertEquals(entries.size(), numOfEntries);
  }
Example #9
0
  /** testGenericInsertFindDelete */
  @Test
  public void testGenericInsertFindDelete() {
    // create resource, identity and group
    OLATResource ores = JunitTestHelper.createRandomResource();
    Identity identity =
        JunitTestHelper.createAndPersistIdentityAsUser("prop-1-" + UUID.randomUUID().toString());
    BusinessGroup group =
        businessGroupService.createBusinessGroup(
            identity, "a buddygroup", "a desc", -1, -1, false, false, null);
    dbInstance.commitAndCloseSession();

    Property p =
        pm.createPropertyInstance(
            identity,
            group,
            ores,
            "catgeneric",
            "TestProperty",
            new Float(1.1),
            new Long(123456),
            "stringValue",
            "textValue");
    pm.saveProperty(p);
    dbInstance.commitAndCloseSession();

    p = pm.findProperty(identity, group, ores, "catgeneric", "TestProperty");
    assertNotNull(p);
    assertEquals(p.getStringValue(), "stringValue");
    assertEquals(p.getFloatValue(), new Float(1.1));
    assertEquals(p.getLongValue(), new Long(123456));
    assertEquals(p.getTextValue(), "textValue");

    pm.deleteProperty(p);
    p = pm.findProperty(identity, group, ores, "catgeneric", "TestProperty");
    assertNull(p);
  }
  /**
   * @see
   *     org.olat.core.gui.components.form.flexible.impl.FormBasicController#validateFormLogic(org.olat.core.gui.UserRequest)
   */
  @Override
  public boolean validateFormLogic(UserRequest ureq) {
    // 1) Check valid group names
    if (!StringHelper.containsNonWhitespace(businessGroupName.getValue())) {
      businessGroupName.setErrorKey("form.legende.mandatory", new String[] {});
      return false;
    }

    if (bulkMode) {
      // check all names to be valid and check that at least one is entered
      // e.g. find "," | " , " | ",,," errors => no group entered
      String selectionAsCsvStr = businessGroupName.getValue();
      String[] activeSelection =
          selectionAsCsvStr != null ? selectionAsCsvStr.split(",") : new String[] {};
      validNames = new HashSet<String>();
      Set<String> wrongNames = new HashSet<String>();
      boolean nameTooLong = false;
      for (int i = 0; i < activeSelection.length; i++) {
        String currentName = activeSelection[i].trim();
        if (currentName.getBytes().length > BusinessGroup.MAX_GROUP_NAME_LENGTH) {
          nameTooLong = true;
        } else if ((currentName).matches(BusinessGroup.VALID_GROUPNAME_REGEXP)) {
          validNames.add(currentName);
        } else {
          wrongNames.add(currentName);
        }
      }
      if (validNames.size() == 0 && wrongNames.size() == 0 && !nameTooLong) {
        // no valid name and no invalid names, this is no names
        businessGroupName.setErrorKey("create.form.error.illegalName", new String[] {});
        return false;
      } else if (nameTooLong) {
        businessGroupName.setErrorKey(
            "create.form.error.nameTooLong",
            new String[] {BusinessGroup.MAX_GROUP_NAME_LENGTH + ""});
        return false;
      } else if (wrongNames.size() == 1) {
        // one invalid name
        businessGroupName.setErrorKey("create.form.error.illegalName", new String[] {});
        return false;
      } else if (wrongNames.size() > 1) {
        // two or more invalid names
        String[] args = new String[] {StringHelper.formatAsCSVString(wrongNames)};
        businessGroupName.setErrorKey("create.form.error.illegalNames", args);
        return false;
      }
    } else {
      String groupName = businessGroupName.getValue();
      if (groupName.getBytes().length > BusinessGroup.MAX_GROUP_NAME_LENGTH) {
        businessGroupName.setErrorKey(
            "create.form.error.nameTooLong",
            new String[] {BusinessGroup.MAX_GROUP_NAME_LENGTH + ""});
        return false;
      } else if (!(groupName).matches(BusinessGroup.VALID_GROUPNAME_REGEXP)) {
        businessGroupName.setErrorKey("create.form.error.illegalName", new String[] {});
        return false;
      }
      if (businessGroupName.hasError()) {
        return false; // auto-validations from form, return false, because of that
                      // clearError()-calls everywhere...
      }
    }
    // all group name tests passed
    businessGroupName.clearError();

    // 2) Check valid description
    if (businessGroupDescription.getValue().length() > 4000) {
      businessGroupDescription.setErrorKey("input.toolong", new String[] {"4000"});
      return false;
    }
    businessGroupDescription.clearError();

    // 3) Check auto close settings
    boolean disableWaitingListOk = true;
    if (businessGroup != null) {
      int waitingPartipiciantSize =
          businessGroupService.countMembers(businessGroup, GroupRoles.waiting.name());
      if ((businessGroup.getWaitingListEnabled()).booleanValue()
          && !isWaitingListEnabled()
          && (waitingPartipiciantSize > 0)) {
        enableAutoCloseRanks.setErrorKey("form.error.disableNonEmptyWaitingList", new String[] {});
        disableWaitingListOk = false;
        setEnableWaitingList(true);
        return false;
      }
    }
    enableAutoCloseRanks.clearError();

    if (disableWaitingListOk) {
      // 4) Check min / max settings
      String maxValue = null;
      if (StringHelper.containsNonWhitespace(businessGroupMaximumMembers.getValue())) {
        maxValue = businessGroupMaximumMembers.getValue();
      }
      String minValue = null;
      if (StringHelper.containsNonWhitespace(businessGroupMinimumMembers.getValue())) {
        minValue = businessGroupMinimumMembers.getValue();
      }
      if (isWaitingListEnabled() && (maxValue == null || minValue == "")) {
        enableWaitingList.setErrorKey("create.form.error.enableWaitinglist", new String[] {});
        return false;
      }
      enableWaitingList.clearError();

      // 5) Check auto close - waiting list dependency
      if (isAutoCloseRanksEnabled() && !isWaitingListEnabled()) {
        enableAutoCloseRanks.setErrorKey("create.form.error.enableAutoCloseRanks", new String[] {});
        return false;
      }
      enableAutoCloseRanks.clearError();

      // 6) Check min/max validity
      if (!businessGroupMaximumMembers
          .getValue()
          .matches("^\\p{Space}*(\\p{Digit}*)\\p{Space}*$")) {
        businessGroupMaximumMembers.setErrorKey("create.form.error.numberOrNull", new String[] {});
        return false;
      }
      if (!businessGroupMinimumMembers
          .getValue()
          .matches("^\\p{Space}*(\\p{Digit}*)\\p{Space}*$")) {
        businessGroupMaximumMembers.setErrorKey("create.form.error.numberOrNull", new String[] {});
        return false;
      }
      businessGroupMaximumMembers.clearError();
    }
    // group name duplication test passed
    businessGroupName.clearError();

    // all checks passed
    return true;
  }
  @Test
  public void deleteCourseSoftly() {
    Identity coach = JunitTestHelper.createAndPersistIdentityAsRndUser("re-soft-");
    Identity coachGroup = JunitTestHelper.createAndPersistIdentityAsRndUser("re-soft-");
    Identity participant = JunitTestHelper.createAndPersistIdentityAsRndUser("re-soft-");
    Identity initialAuthor = JunitTestHelper.createAndPersistIdentityAsRndUser("auth-del-1");
    RepositoryEntry re = JunitTestHelper.deployDemoCourse(initialAuthor);
    dbInstance.commitAndCloseSession();

    // add business group
    BusinessGroup group =
        businessGroupService.createBusinessGroup(
            coachGroup, "Relation 1", "tg", null, null, false, false, re);
    businessGroupService.addResourceTo(group, re);
    dbInstance.commit();

    // catalog
    List<CatalogEntry> rootEntries = catalogManager.getRootCatalogEntries();
    CatalogEntry catEntry = catalogManager.createCatalogEntry();
    catEntry.setName("Soft");
    catEntry.setRepositoryEntry(re);
    catEntry.setParent(rootEntries.get(0));
    catEntry.setOwnerGroup(securityManager.createAndPersistSecurityGroup());
    catalogManager.saveCatalogEntry(catEntry);
    dbInstance.commit();

    // check the catalog
    List<CatalogEntry> catEntries = catalogManager.getCatalogCategoriesFor(re);
    Assert.assertNotNull(catEntries);
    Assert.assertEquals(1, catEntries.size());

    // add owner, coach...
    repositoryEntryRelationDao.addRole(coach, re, GroupRoles.coach.name());
    repositoryEntryRelationDao.addRole(participant, re, GroupRoles.participant.name());
    dbInstance.commit();

    // kill it softly like A. Keys
    repositoryService.deleteSoftly(re, initialAuthor, false);
    dbInstance.commit();

    // check that the members are removed
    List<Identity> coachAndParticipants =
        repositoryEntryRelationDao.getMembers(
            re,
            RepositoryEntryRelationType.both,
            GroupRoles.coach.name(),
            GroupRoles.participant.name());
    Assert.assertNotNull(coachAndParticipants);
    Assert.assertEquals(0, coachAndParticipants.size());

    // check the relations between course and business groups
    SearchBusinessGroupParams params = new SearchBusinessGroupParams();
    List<BusinessGroup> groups = businessGroupService.findBusinessGroups(params, re, 0, -1);
    Assert.assertNotNull(groups);
    Assert.assertEquals(0, groups.size());

    // check the catalog
    List<CatalogEntry> removedCatEntries = catalogManager.getCatalogCategoriesFor(re);
    Assert.assertNotNull(removedCatEntries);
    Assert.assertEquals(0, removedCatEntries.size());

    RepositoryEntry reloadEntry = repositoryService.loadByKey(re.getKey());
    Assert.assertNotNull(reloadEntry);
    Assert.assertEquals(0, reloadEntry.getAccess());
    Assert.assertNotNull(reloadEntry.getDeletionDate());
    Assert.assertEquals(initialAuthor, reloadEntry.getDeletedBy());
  }
Example #12
0
  @Test
  public void testFindIdentities() {
    // create identities, group and resource
    OLATResource res = JunitTestHelper.createRandomResource();
    Identity id1 =
        JunitTestHelper.createAndPersistIdentityAsUser("prop-7-" + UUID.randomUUID().toString());
    Identity id2 =
        JunitTestHelper.createAndPersistIdentityAsUser("prop-10-" + UUID.randomUUID().toString());
    Identity id3 =
        JunitTestHelper.createAndPersistIdentityAsUser("prop-11-" + UUID.randomUUID().toString());
    Identity id4 =
        JunitTestHelper.createAndPersistIdentityAsUser("prop-12-" + UUID.randomUUID().toString());
    BusinessGroup group =
        businessGroupService.createBusinessGroup(
            id1, "a buddygroup", "a desc", -1, -1, false, false, null);
    dbInstance.commitAndCloseSession();

    String propName = UUID.randomUUID().toString();

    Property p =
        pm.createPropertyInstance(
            id1,
            group,
            res,
            "cat",
            propName,
            new Float(1.1),
            new Long(123456),
            "stringValue",
            "textValue");
    pm.saveProperty(p);
    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",
            propName,
            new Float(1.1),
            new Long(123456),
            "stringValue",
            "textValue");
    pm.saveProperty(p);
    p =
        pm.createPropertyInstance(
            id4,
            group,
            res,
            "cat",
            propName,
            new Float(1.1),
            new Long(123456),
            "stringValue",
            "textValue");
    pm.saveProperty(p);
    p =
        pm.createPropertyInstance(
            id1,
            group,
            res,
            "cat2",
            propName,
            new Float(1.1),
            new Long(123456),
            "stringValue",
            "textValue");
    pm.saveProperty(p);
    p =
        pm.createPropertyInstance(
            id2,
            group,
            res,
            "cat2",
            propName,
            new Float(1.1),
            new Long(123456),
            "stringValue",
            "textValue");
    pm.saveProperty(p);

    dbInstance.commitAndCloseSession();
    // now find identities
    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());
  }
Example #13
0
  /**
   * testFloatValues THIS test does only success when you run it against mysql with FLOAT(65,30).
   * FLOAT(65,30) is mysql specific and if you let hibernate generate the tables automatic it will
   * result in FLOAT only and this test will fail. So this means that you have to populate the
   * tables yourself via the sql file.
   */
  @Test
  public void testFloatValues() {
    // create identity, group and resource
    OLATResource res = JunitTestHelper.createRandomResource();
    Identity identity =
        JunitTestHelper.createAndPersistIdentityAsUser("prop-6-" + UUID.randomUUID().toString());
    BusinessGroup group =
        businessGroupService.createBusinessGroup(
            identity, "a buddygroup", "a desc", -1, -1, false, false, null);
    dbInstance.commitAndCloseSession();

    Property original, copy;
    // gs:changed to FLOAT(65,30) to be compatible with hsqldb and auto generated ddl
    // Define my own MAX float value because the db precision changed from DECIMAL(78,36) to
    // DECIMAL(65,30)
    double floatMaxValue = 1E34; // 1E35 does failed with mysql 5.0.x
    original =
        pm.createPropertyInstance(
            identity,
            group,
            res,
            "cat",
            "TestProperty",
            new Float(1234534343424213.1324534533456),
            new Long(123456),
            "stringValue",
            "textValue");
    pm.saveProperty(original);
    // DBFactory.getInstance().evict(original);
    dbInstance.commitAndCloseSession();
    copy = pm.findProperty(identity, group, res, "cat", "TestProperty");
    float f1F = original.getFloatValue().floatValue();
    float copyF = copy.getFloatValue().floatValue();
    assertEquals("values differ:" + f1F + ", and " + copyF, f1F, copyF, 0.0000000001f);
    pm.deleteProperties(identity, group, res, "cat", "TestProperty");

    // note: on mysql 5.0, the standard installation is strict mode, which reports any data
    // truncation error as a real jdbc error.
    // -1e35 seems out of range for DECIMAL(65,30) so data truncation occurs???
    //                                          +-> 30 digits to the right side of decimal point
    // From mysql:
    // The declaration syntax for a DECIMAL column is DECIMAL(M,D). The ranges of values for the
    // arguments in MySQL 5.1 are as follows:
    // M is the maximum number of digits (the precision). It has a range of 1 to 65. (Older versions
    // of MySQL allowed a range of 1 to 254.)
    // D is the number of digits to the right of the decimal point (the scale). It has a range of 0
    // to 30 and must be no larger than M.
    original =
        pm.createPropertyInstance(
            identity,
            group,
            res,
            "cat",
            "TestProperty",
            new Float(-floatMaxValue),
            new Long(123456),
            "stringValue",
            "textValue");
    pm.saveProperty(original);
    dbInstance.commitAndCloseSession();
    copy =
        pm.findProperty(
            identity,
            group,
            res,
            "cat",
            "TestProperty"); // this one failes at the moment for hsqldb with: incompatible data
                             // type in conversion: from SQL type DECIMAL to java.lang.Double,
                             // value:
                             // -9999999790214767953607394487959552.000000000000000000000000000000
    assertTrue(original.getFloatValue().floatValue() == copy.getFloatValue().floatValue());
    pm.deleteProperties(identity, group, res, "cat", "TestProperty");

    original =
        pm.createPropertyInstance(
            identity,
            group,
            res,
            "cat",
            "TestProperty",
            new Float(floatMaxValue),
            new Long(123456),
            "stringValue",
            "textValue");
    pm.saveProperty(original);
    dbInstance.commitAndCloseSession();
    copy = pm.findProperty(identity, group, res, "cat", "TestProperty");
    assertTrue(original.getFloatValue().floatValue() == copy.getFloatValue().floatValue());
    pm.deleteProperties(identity, group, res, "cat", "TestProperty");

    original =
        pm.createPropertyInstance(
            identity,
            group,
            res,
            "cat",
            "TestProperty",
            new Float(Long.MAX_VALUE),
            new Long(123456),
            "stringValue",
            "textValue");
    pm.saveProperty(original);
    dbInstance.commitAndCloseSession();
    copy = pm.findProperty(identity, group, res, "cat", "TestProperty");
    assertTrue(original.getFloatValue().floatValue() == copy.getFloatValue().floatValue());
    pm.deleteProperties(identity, group, res, "cat", "TestProperty");

    original =
        pm.createPropertyInstance(
            identity,
            group,
            res,
            "cat",
            "TestProperty",
            new Float(Long.MIN_VALUE),
            new Long(123456),
            "stringValue",
            "textValue");
    pm.saveProperty(original);
    dbInstance.commitAndCloseSession();
    copy = pm.findProperty(identity, group, res, "cat", "TestProperty");
    assertTrue(original.getFloatValue().floatValue() == copy.getFloatValue().floatValue());
    pm.deleteProperties(identity, group, res, "cat", "TestProperty");
  }
Example #14
0
  /**
   * Performance test of 500 propertycreations per type. Rename to testPerf500Properties to include
   * this test in the test suit.
   */
  @Test
  public void testPerf500Properties() {
    // create identity, group and resource
    OLATResource res = JunitTestHelper.createRandomResource();
    Identity identity =
        JunitTestHelper.createAndPersistIdentityAsUser("prop-5-" + UUID.randomUUID().toString());
    BusinessGroup group =
        businessGroupService.createBusinessGroup(
            identity, "a buddygroup", "a desc", -1, -1, false, false, null);
    dbInstance.commitAndCloseSession();

    long start, stop;
    long count = 500;

    // create generic proerties
    log.info("----------------------------------------------------------------");
    log.info("Performance test startet. Running " + count + " cycles per test.");
    log.info("CREATE generic property test started...");
    start = System.currentTimeMillis();
    for (int i = 0; i < count; i++) {
      Property p =
          pm.createPropertyInstance(
              identity,
              group,
              res,
              "perf500",
              "TestProperty" + i,
              new Float(1.1),
              new Long(123456),
              "stringValue",
              "textValue");
      pm.saveProperty(p);

      if (i % 50 == 0) {
        dbInstance.commitAndCloseSession();
      }
    }
    dbInstance.commitAndCloseSession();

    stop = System.currentTimeMillis();
    log.info(
        "CREATE generic property test: "
            + (stop - start)
            + " ms ("
            + (count * 1000 / (stop - start))
            + "/sec)");
    // some find identitites tests
    List<Identity> ids = pm.findIdentitiesWithProperty(null, null, "perf500", null, false);
    Assert.assertNotNull("Identities cannot be null", ids);
    Assert.assertFalse("Identities cannot be empty", ids.isEmpty());
    Assert.assertTrue("Identities must contains reference identity", ids.contains(identity));

    // create course and user properties
    log.info("Preparing user/group properties test. Creating additional properties..");
    start = System.currentTimeMillis();
    for (int i = 0; i < count; i++) {
      Property pUser =
          pm.createUserPropertyInstance(
              identity,
              "perf500",
              "TestProperty" + i,
              new Float(1.1),
              new Long(123456),
              "stringValue",
              "textValue");
      pm.saveProperty(pUser);
      if (i % 50 == 0) {
        dbInstance.commitAndCloseSession();
      }
    }
    dbInstance.commitAndCloseSession();

    stop = System.currentTimeMillis();
    log.info("Ready : " + (stop - start) + " ms (" + (2 * count * 1000 / (stop - start)) + "/sec)");
    log.info("Starting find tests. DB holds " + count * 3 + " records.");

    // find generic property test
    log.info("FIND generic property test started...");
    start = System.currentTimeMillis();
    for (int i = 0; i < count; i++) {
      Property p = pm.findProperty(identity, group, res, "perf500", "TestProperty" + i);
      assertNotNull("Must find the p (count=" + i + ")", p);
      dbInstance.commitAndCloseSession();
    }
    stop = System.currentTimeMillis();
    log.info(
        "FIND generic property test: "
            + (stop - start)
            + " ms ("
            + (count * 1000 / (stop - start))
            + "/sec)");

    // find user property test
    log.info("FIND user property test started...");
    start = System.currentTimeMillis();
    for (int i = 0; i < count; i++) {
      Property p = pm.findUserProperty(identity, "perf500", "TestProperty" + i);
      assertNotNull("Must find the p (count=" + i + ")", p);
      dbInstance.commitAndCloseSession();
    }
    stop = System.currentTimeMillis();
    log.info(
        "FIND user property test: "
            + (stop - start)
            + " ms ("
            + (count * 1000 / (stop - start))
            + "/sec)");

    // find & delete
    log.info("FIND and DELETE generic property test started...");
    start = System.currentTimeMillis();
    for (int i = 0; i < count; i++) {
      Property p = pm.findUserProperty(identity, "perf500", "TestProperty" + i);
      pm.deleteProperty(p);
    }
    stop = System.currentTimeMillis();
    log.info(
        "FIND and DELETE generic property test: "
            + (stop - start)
            + " ms ("
            + (count * 1000 / (stop - start))
            + "/sec)");

    log.info("----------------------------------------------------------------");
    log.info("Performance test finished.");
  }
Example #15
0
  @Override
  public List<CalendarFileInfos> getListOfCalendarsFiles(Identity identity) {
    List<CalendarFileInfos> aggregatedFiles = new ArrayList<>();

    Map<CalendarKey, CalendarUserConfiguration> configMap =
        calendarManager.getCalendarUserConfigurationsMap(identity);

    // personal calendar
    CalendarKey personalCalendarKey =
        new CalendarKey(identity.getName(), CalendarManager.TYPE_USER);
    CalendarUserConfiguration personalCalendarConfig = configMap.get(personalCalendarKey);
    if (calendarModule.isEnablePersonalCalendar()
        && (personalCalendarConfig == null || personalCalendarConfig.isInAggregatedFeed())) {
      File iCalFile =
          calendarManager.getCalendarICalFile(CalendarManager.TYPE_USER, identity.getName());
      if (iCalFile != null) {
        aggregatedFiles.add(
            new CalendarFileInfos(identity.getName(), CalendarManager.TYPE_USER, iCalFile));
      }

      // reload every hour
      List<CalendarFileInfos> importedCalendars =
          importCalendarManager.getImportedCalendarInfosForIdentity(identity, true);
      aggregatedFiles.addAll(importedCalendars);
    }

    // group calendars
    if (calendarModule.isEnableGroupCalendar()) {
      SearchBusinessGroupParams groupParams = new SearchBusinessGroupParams(identity, true, true);
      groupParams.addTools(CollaborationTools.TOOL_CALENDAR);
      List<BusinessGroup> groups =
          businessGroupService.findBusinessGroups(groupParams, null, 0, -1);
      for (BusinessGroup group : groups) {
        String calendarId = group.getKey().toString();
        CalendarKey key = new CalendarKey(calendarId, CalendarManager.TYPE_GROUP);
        CalendarUserConfiguration calendarConfig = configMap.get(key);
        if (calendarConfig == null || calendarConfig.isInAggregatedFeed()) {
          File iCalFile =
              calendarManager.getCalendarICalFile(CalendarManager.TYPE_GROUP, calendarId);
          if (iCalFile != null) {
            aggregatedFiles.add(
                new CalendarFileInfos(calendarId, CalendarManager.TYPE_GROUP, iCalFile));
          }
        }
      }
    }

    if (calendarModule.isEnableCourseElementCalendar()
        || calendarModule.isEnableCourseToolCalendar()) {
      List<Object[]> resources = getCourses(identity);
      for (Object[] resource : resources) {
        RepositoryEntry courseEntry = (RepositoryEntry) resource[0];
        String calendarId = courseEntry.getOlatResource().getResourceableId().toString();
        CalendarKey key = new CalendarKey(calendarId, CalendarManager.TYPE_COURSE);
        CalendarUserConfiguration calendarConfig = configMap.get(key);
        if (calendarConfig == null || calendarConfig.isInAggregatedFeed()) {
          File iCalFile =
              calendarManager.getCalendarICalFile(CalendarManager.TYPE_COURSE, calendarId);
          if (iCalFile != null) {
            aggregatedFiles.add(
                new CalendarFileInfos(calendarId, CalendarManager.TYPE_COURSE, iCalFile));
          }
        }
      }
    }

    return aggregatedFiles;
  }
  /** @return True if all results are the same */
  private ModelInfos loadModel() {
    // load participants, load datas
    ICourse course = CourseFactory.loadCourse(courseEnv.getCourseResourceableId());
    List<Identity> identities =
        businessGroupService.getMembers(assessedGroup, GroupRoles.participant.name());

    Map<Identity, AssessmentEntry> identityToEntryMap = new HashMap<>();
    List<AssessmentEntry> entries =
        course
            .getCourseEnvironment()
            .getAssessmentManager()
            .getAssessmentEntries(assessedGroup, gtaNode);
    for (AssessmentEntry entry : entries) {
      identityToEntryMap.put(entry.getIdentity(), entry);
    }

    int count = 0;
    boolean same = true;
    StringBuilder duplicateWarning = new StringBuilder();
    Float scoreRef = null;
    Boolean passedRef = null;
    String commentRef = null;

    List<AssessmentRow> rows = new ArrayList<>(identities.size());
    for (Identity identity : identities) {
      AssessmentEntry entry = identityToEntryMap.get(identity);

      ScoreEvaluation scoreEval = null;
      if (withScore || withPassed) {
        scoreEval = gtaNode.getUserScoreEvaluation(entry);
        if (scoreEval == null) {
          scoreEval = ScoreEvaluation.EMPTY_EVALUATION;
        }
      }

      String comment = null;
      if (withComment && entry != null) {
        comment = entry.getComment();
      }

      boolean duplicate = duplicateMemberKeys.contains(identity.getKey());
      if (duplicate) {
        if (duplicateWarning.length() > 0) duplicateWarning.append(", ");
        duplicateWarning.append(StringHelper.escapeHtml(userManager.getUserDisplayName(identity)));
      }

      AssessmentRow row = new AssessmentRow(identity, duplicate);
      rows.add(row);

      if (withScore) {
        Float score = scoreEval.getScore();
        String pointVal = AssessmentHelper.getRoundedScore(score);
        TextElement pointEl = uifactory.addTextElement("point" + count, null, 5, pointVal, flc);
        pointEl.setDisplaySize(5);
        row.setScoreEl(pointEl);
        if (count == 0) {
          scoreRef = score;
        } else if (!same(scoreRef, score)) {
          same = false;
        }
      }

      if (withPassed && cutValue == null) {
        Boolean passed = scoreEval.getPassed();
        MultipleSelectionElement passedEl =
            uifactory.addCheckboxesHorizontal("check" + count, null, flc, onKeys, onValues);
        if (passed != null && passed.booleanValue()) {
          passedEl.select(onKeys[0], passed.booleanValue());
        }
        row.setPassedEl(passedEl);
        if (count == 0) {
          passedRef = passed;
        } else if (!same(passedRef, passed)) {
          same = false;
        }
      }

      if (withComment) {
        FormLink commentLink =
            uifactory.addFormLink(
                "comment-" + CodeHelper.getRAMUniqueID(),
                "comment",
                "comment",
                null,
                flc,
                Link.LINK);
        if (StringHelper.containsNonWhitespace(comment)) {
          commentLink.setIconLeftCSS("o_icon o_icon_comments");
        } else {
          commentLink.setIconLeftCSS("o_icon o_icon_comments_none");
        }
        commentLink.setUserObject(row);
        row.setComment(comment);
        row.setCommentEditLink(commentLink);

        if (count == 0) {
          commentRef = comment;
        } else if (!same(commentRef, comment)) {
          same = false;
        }
      }

      count++;
    }

    model.setObjects(rows);
    table.reset();

    return new ModelInfos(same, scoreRef, passedRef, commentRef, duplicateWarning.toString());
  }
  /**
   * @see
   *     org.olat.core.commons.services.notifications.NotificationsHandler#createSubscriptionInfo(org.olat.core.commons.services.notifications.Subscriber,
   *     java.util.Locale, java.util.Date)
   */
  public SubscriptionInfo createSubscriptionInfo(
      final Subscriber subscriber, Locale locale, Date compareDate) {
    SubscriptionInfo si = null;
    Publisher p = subscriber.getPublisher();
    if (!NotificationsUpgradeHelper.checkCourse(p)) {
      // course don't exist anymore
      NotificationsManager.getInstance().deactivate(p);
      return NotificationsManager.getInstance().getNoSubscriptionInfo();
    }

    try {
      Date latestNews = p.getLatestNewsDate();
      Identity identity = subscriber.getIdentity();

      // do not try to create a subscription info if state is deleted - results in
      // exceptions, course
      // can't be loaded when already deleted
      if (NotificationsManager.getInstance().isPublisherValid(p)
          && compareDate.before(latestNews)) {
        Long courseId = new Long(p.getData());
        final ICourse course = loadCourseFromId(courseId);
        if (course != null) {
          // course admins or users with the course right to have full access to
          // the assessment tool will have full access to user tests
          CourseGroupManager cgm = course.getCourseEnvironment().getCourseGroupManager();
          final boolean hasFullAccess =
              (cgm.isIdentityCourseAdministrator(identity)
                  ? true
                  : cgm.hasRight(identity, CourseRights.RIGHT_ASSESSMENT));
          final List<Identity> coachedUsers = new ArrayList<Identity>();
          if (!hasFullAccess) {
            // initialize list of users, only when user has not full access
            List<BusinessGroup> coachedGroups = cgm.getOwnedBusinessGroups(identity);
            BusinessGroupService businessGroupService =
                CoreSpringFactory.getImpl(BusinessGroupService.class);
            List<Identity> coachedIdentites =
                businessGroupService.getMembers(coachedGroups, GroupRoles.participant.name());
            coachedUsers.addAll(coachedIdentites);
          }

          List<AssessableCourseNode> testNodes = getCourseTestNodes(course);
          Translator translator =
              Util.createPackageTranslator(AssessmentNotificationsHandler.class, locale);

          for (AssessableCourseNode test : testNodes) {
            final CoursePropertyManager cpm =
                course.getCourseEnvironment().getCoursePropertyManager();

            List<Property> scoreProperties =
                cpm.listCourseNodeProperties(test, null, null, AssessmentManager.SCORE);
            List<Property> attemptProperties =
                cpm.listCourseNodeProperties(test, null, null, AssessmentManager.ATTEMPTS);

            for (Property attemptProperty : attemptProperties) {
              Date modDate = attemptProperty.getLastModified();
              Identity assessedIdentity = attemptProperty.getIdentity();
              if (modDate.after(compareDate)
                  && (hasFullAccess
                      || PersistenceHelper.listContainsObjectByKey(
                          coachedUsers, assessedIdentity))) {
                String score = null;
                for (Property scoreProperty : scoreProperties) {
                  if (scoreProperty.getIdentity().equalsByPersistableKey(assessedIdentity)) {
                    score = scoreProperty.getFloatValue().toString();
                    break;
                  }
                }

                if (test instanceof ScormCourseNode) {
                  ScormCourseNode scormTest = (ScormCourseNode) test;
                  // check if completed or passed
                  String status =
                      ScormAssessmentManager.getInstance()
                          .getLastLessonStatus(
                              assessedIdentity.getName(), course.getCourseEnvironment(), scormTest);
                  if (!"passed".equals(status) && !"completed".equals(status)) {
                    continue;
                  }
                }

                String desc;
                String type = translator.translate("notifications.entry." + test.getType());
                if (score == null) {
                  desc =
                      translator.translate(
                          "notifications.entry.attempt",
                          new String[] {
                            test.getShortTitle(),
                            NotificationHelper.getFormatedName(assessedIdentity),
                            type
                          });
                } else {
                  desc =
                      translator.translate(
                          "notifications.entry",
                          new String[] {
                            test.getShortTitle(),
                            NotificationHelper.getFormatedName(assessedIdentity),
                            score,
                            type
                          });
                }

                String urlToSend = null;
                String businessPath = null;
                if (p.getBusinessPath() != null) {
                  businessPath =
                      p.getBusinessPath()
                          + "[assessmentTool:0][Identity:"
                          + assessedIdentity.getKey()
                          + "][CourseNode:"
                          + test.getIdent()
                          + "]";
                  urlToSend =
                      BusinessControlFactory.getInstance()
                          .getURLFromBusinessPathString(businessPath);
                }

                SubscriptionListItem subListItem =
                    new SubscriptionListItem(
                        desc, urlToSend, businessPath, modDate, CSS_CLASS_USER_ICON);
                if (si == null) {
                  String title =
                      translator.translate(
                          "notifications.header", new String[] {course.getCourseTitle()});
                  String css =
                      CourseNodeFactory.getInstance()
                          .getCourseNodeConfigurationEvenForDisabledBB(test.getType())
                          .getIconCSSClass();
                  si =
                      new SubscriptionInfo(
                          subscriber.getKey(), p.getType(), new TitleItem(title, css), null);
                }
                si.addSubscriptionListItem(subListItem);
              }
            }
          }
        }
      }
      if (si == null) {
        si = NotificationsManager.getInstance().getNoSubscriptionInfo();
      }
      return si;
    } catch (Exception e) {
      log.error("Error while creating assessment notifications", e);
      checkPublisher(p);
      return NotificationsManager.getInstance().getNoSubscriptionInfo();
    }
  }