@Override
  protected void formOK(UserRequest ureq) {
    commitFields();
    commitStepLabels();

    String selectedType = typeEl.getSelectedKey();
    SliderType type = SliderType.valueOf(selectedType);
    rubric.setSliderType(type);
    if (type == SliderType.continuous) {
      rubric.setStart(1);
      rubric.setEnd(100);
      rubric.setSteps(100);
    } else {
      int steps = Integer.parseInt(stepsEl.getSelectedKey());
      rubric.setStart(1);
      rubric.setEnd(steps);
      rubric.setSteps(steps);
    }

    for (Iterator<Slider> sliderIt = rubric.getSliders().iterator(); sliderIt.hasNext(); ) {
      Slider slider = sliderIt.next();
      if (!StringHelper.containsNonWhitespace(slider.getStartLabel())
          && !StringHelper.containsNonWhitespace(slider.getEndLabel())) {
        sliderIt.remove();
      }
    }

    rubricCtrl.updateForm();

    fireEvent(ureq, new ChangePartEvent(rubric));
    fireEvent(ureq, new ClosePartEvent(rubric));
  }
Esempio n. 2
0
 @Override
 public void render(
     final StringOutput sb,
     final Renderer renderer,
     final Object val,
     final Locale locale,
     final int alignment,
     final String action) {
   if (renderer == null) {
     // render for export
     String value = getCellValue(val);
     if (!StringHelper.containsNonWhitespace(value)) {
       value = getHoverText(val);
     }
     sb.append(value);
   } else {
     sb.append("<i class='").append(getCssClass(val)).append("'> </i> <span");
     String hoverText = getHoverText(val);
     if (StringHelper.containsNonWhitespace(hoverText)) {
       sb.append(" title=\"");
       sb.append(StringEscapeUtils.escapeHtml(hoverText));
     }
     sb.append("\">");
     sb.append(getCellValue(val));
     sb.append("</span>");
   }
 }
 @Override
 public boolean isIpAllowed(String ipList, String address) {
   boolean allOk = false;
   if (!StringHelper.containsNonWhitespace(ipList)) {
     allOk |= true;
   } else {
     for (StringTokenizer tokenizer = new StringTokenizer(ipList, "\n\r", false);
         tokenizer.hasMoreTokens(); ) {
       String ipRange = tokenizer.nextToken();
       if (StringHelper.containsNonWhitespace(ipRange)) {
         int indexMask = ipRange.indexOf("/");
         int indexPseudoRange = ipRange.indexOf("-");
         if (indexMask > 0) {
           allOk |= IPUtils.isValidRange(ipRange, address);
         } else if (indexPseudoRange > 0) {
           String begin = ipRange.substring(0, indexPseudoRange).trim();
           String end = ipRange.substring(indexPseudoRange + 1).trim();
           allOk |= IPUtils.isValidRange(begin, end, address);
         } else {
           allOk |= ipRange.equals(address);
         }
       }
     }
   }
   return allOk;
 }
Esempio n. 4
0
  @Override
  public boolean isInterceptionRequired(UserRequest ureq) {
    UserSession usess = ureq.getUserSession();

    boolean interception = false;
    if (isREST(ureq)) {
      // do nothing
    } else if (!historyModule.isResumeEnabled()) {
      String bc = getLandingBC(ureq);
      launch(ureq, bc);
    } else if (usess.getRoles().isGuestOnly()) {
      String bc = getLandingBC(ureq);
      launch(ureq, bc);
    } else {
      Preferences prefs = usess.getGuiPreferences();
      String resumePrefs = (String) prefs.get(WindowManager.class, "resume-prefs");
      if (!StringHelper.containsNonWhitespace(resumePrefs)) {
        resumePrefs = historyModule.getResumeDefaultSetting();
      }

      if ("none".equals(resumePrefs)) {
        String bc = getLandingBC(ureq);
        launch(ureq, bc);
      } else if ("auto".equals(resumePrefs)) {
        HistoryPoint historyEntry =
            HistoryManager.getInstance().readHistoryPoint(ureq.getIdentity());
        if (historyEntry != null
            && StringHelper.containsNonWhitespace(historyEntry.getBusinessPath())) {
          List<ContextEntry> cloneCes =
              BusinessControlFactory.getInstance().cloneContextEntries(historyEntry.getEntries());
          BusinessControl bc =
              BusinessControlFactory.getInstance().createFromContextEntries(cloneCes);
          launch(ureq, bc);
        } else {
          String bc = getLandingBC(ureq);
          launch(ureq, bc);
        }
      } else if ("ondemand".equals(resumePrefs)) {
        HistoryPoint historyEntry = historyManager.readHistoryPoint(ureq.getIdentity());
        if (historyEntry != null
            && StringHelper.containsNonWhitespace(historyEntry.getBusinessPath())) {
          interception = true;

          String bc = getLandingBC(ureq);
          if (StringHelper.containsNonWhitespace(bc)) {
            noButton.setVisible(false);
          } else {
            landingButton.setVisible(false);
          }
        } else {
          String bc = getLandingBC(ureq);
          launch(ureq, bc);
        }
      }
    }
    return interception;
  }
Esempio n. 5
0
  /**
   * Resolves a file path in the base container or creates this file under the given path. The
   * method creates any missing directories.
   *
   * @param baseContainer The base directory. User must have write permissions on this container
   * @param relFilePath The path relative to the base container. Must start with a '/'. To separate
   *     sub directories use '/'
   * @return The resolved or created leaf or NULL if a problem happened
   */
  public static VFSLeaf resolveOrCreateLeafFromPath(
      VFSContainer baseContainer, String relFilePath) {
    if (StringHelper.containsNonWhitespace(relFilePath)) {
      int lastSlash = relFilePath.lastIndexOf("/");
      String relDirPath = relFilePath;
      String fileName = null;
      if (lastSlash == -1) {
        // relFilePath is the file name - no directories involved
        relDirPath = null;
        fileName = relFilePath;
      } else if (lastSlash == 0) {
        // Remove start slash from file name
        relDirPath = null;
        fileName = relFilePath.substring(1, relFilePath.length());
      } else {
        relDirPath = relFilePath.substring(0, lastSlash);
        fileName = relFilePath.substring(lastSlash);
      }

      // Create missing directories and set parent dir for later file creation
      VFSContainer parent = baseContainer;
      if (StringHelper.containsNonWhitespace(relDirPath)) {
        parent = resolveOrCreateContainerFromPath(baseContainer, relDirPath);
      }
      // Now create file in that dir
      if (StringHelper.containsNonWhitespace(fileName)) {
        VFSLeaf leaf = null;
        VFSItem resolvedFile = parent.resolve(fileName);
        if (resolvedFile == null) {
          leaf = parent.createChildLeaf(fileName);
          if (leaf == null) {
            log.error(
                "Could not create leaf with relPath::"
                    + relFilePath
                    + " in base container::"
                    + getRealPath(baseContainer),
                null);
          }
        } else {
          if (resolvedFile instanceof VFSLeaf) {
            leaf = (VFSLeaf) resolvedFile;
          } else {
            leaf = null;
            log.error(
                "Could not create relPath::"
                    + relFilePath
                    + ", a directory with this name exists (but not a file) in base container::"
                    + getRealPath(baseContainer),
                null);
          }
        }
        return leaf;
      }
    }
    return null;
  }
Esempio n. 6
0
 /**
  * Search first in the user preferences, after in rules
  *
  * @param ureq
  * @return
  */
 private String getLandingBC(UserRequest ureq) {
   Preferences prefs = ureq.getUserSession().getGuiPreferences();
   String landingPage = (String) prefs.get(WindowManager.class, "landing-page");
   if (StringHelper.containsNonWhitespace(landingPage)) {
     String path = Rules.cleanUpLandingPath(landingPage);
     if (StringHelper.containsNonWhitespace(path)) {
       return BusinessControlFactory.getInstance().formatFromURI(path);
     }
   }
   return lpModule.getRules().match(ureq.getUserSession());
 }
  @Override
  protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) {
    if (formLayout instanceof FormLayoutContainer) {
      FormLayoutContainer layout = (FormLayoutContainer) formLayout;
      layout.contextPut("numOfMembers", Integer.toString(numOfMembers));

      FormLayoutContainer layoutCont =
          FormLayoutContainer.createDefaultFormLayout("confirm", getTranslator());
      formLayout.add("confirm", layoutCont);
      layoutCont.setRootForm(mainForm);

      StringBuilder message = new StringBuilder();
      for (RepositoryEntry row : rows) {
        if (message.length() > 0) message.append(", ");
        message.append(StringHelper.escapeHtml(row.getDisplayname()));
      }

      String[] acknowledge = new String[] {translate("details.read.only.acknowledge.msg")};
      acknowledgeEl =
          uifactory.addCheckboxesHorizontal(
              "confirm",
              "details.read.only.acknowledge",
              layoutCont,
              new String[] {""},
              acknowledge);

      FormLayoutContainer buttonsCont =
          FormLayoutContainer.createButtonLayout("buttons", getTranslator());
      layoutCont.add(buttonsCont);
      uifactory.addFormCancelButton("cancel", buttonsCont, ureq, getWindowControl());
      readOnlyButton = uifactory.addFormLink("details.closed", buttonsCont, Link.BUTTON);
    }
  }
  /**
   * Returns a CSV line for the given LoggingObject - containing all properties in the exact same
   * way as in the config file - excluding those which could not be retrieved, i.e. for which no
   * PropertyDescriptor could be created
   *
   * @param loggingObject the LoggingObject for which a CSV line should be created
   * @return the CSV line representing the given LoggingObject
   */
  public String getCSVRow(LoggingObject loggingObject, boolean anonymize, Long resourceableId) {
    List<String> loggingObjectList = new ArrayList<String>();
    for (Iterator<PropertyDescriptor> it = orderedExportedPropertyDescriptors.iterator();
        it.hasNext(); ) {
      PropertyDescriptor pd = it.next();

      String strValue = "";
      try {
        Object value = pd.getReadMethod().invoke(loggingObject, (Object[]) null);
        if (value != null) {
          strValue = String.valueOf(value);
        }
        if (anonymize && anonymizedProperties.contains(pd.getName())) {
          // do anonymization
          strValue = makeAnonymous(String.valueOf(value), resourceableId);
        }
      } catch (IllegalArgumentException e) {
        // nothing to do
      } catch (IllegalAccessException e) {
        // nothing to do
      } catch (InvocationTargetException e) {
        // nothing to do
      }
      loggingObjectList.add(strValue);
    }

    return StringHelper.formatAsCSVString(loggingObjectList);
  }
Esempio n. 9
0
  /**
   * Helper to create the proposed directory name for the page base on the course node short title.
   * The title is normalized, converted to ASCII and all strange characters are removed. Users
   * should recognize the proposed directory name in most cases. As a fallback, the course node ID
   * is used in case everything is stripped. If a proposed name already exists, the directory will
   * get a number appended. <br>
   * The file name will always be "index.html" <br>
   * The end result will look something like this: <br>
   *
   * <pre>/single_page3/index.html</pre>
   *
   * @param courseNode
   * @param courseFolderBaseContainer
   * @return The proposed relative file path
   */
  public static String createUniqueRelFilePathFromShortTitle(
      CourseNode courseNode, VFSContainer courseFolderBaseContainer) {
    // Normalize course node title to something URL and filesystem safe
    // containing only ASCII characters
    String safePath =
        FileUtils.normalizeFilename(courseNode.getShortTitle().toLowerCase())
            .trim()
            .replaceAll("[^\\p{ASCII}]", "") // delete non-ASCII
            .replaceAll("[\\p{Punct}]+", "_") // replace punctuation characters
            .replaceAll("\\s+", "_") // replace whitespace
            .replaceAll("_+", "_") // multiple replacement strings
            .replaceAll("^_", "") // delete replacement string at beginning
            .replaceAll("_$", "") // delete replacement string at end
            .toLowerCase(Locale.ENGLISH);

    // If string is empty, use node ID instead
    if (!StringHelper.containsNonWhitespace(safePath)) {
      safePath = courseNode.getIdent();
    }

    // Check if directory already exists, if yes, append number at end of
    // directory
    VFSItem direxists = courseFolderBaseContainer.resolve(safePath);
    int i = 1;
    while (direxists != null && i < 100) {
      i++;
      safePath = FileUtils.appendNumberAtTheEndOfFilename(safePath, i);
      direxists = courseFolderBaseContainer.resolve(safePath);
    }

    return "/" + safePath + "/" + safePath + ".html";
  }
Esempio n. 10
0
 @Override
 public void evalFormRequest(UserRequest ureq) {
   String uri = ureq.getModuleURI();
   if (uri == null) {
     QTIWorksAssessmentTestEvent event = null;
     String cmd = ureq.getParameter("cid");
     if (StringHelper.containsNonWhitespace(cmd)) {
       switch (QTIWorksAssessmentTestEvent.Event.valueOf(cmd)) {
         case selectItem:
           {
             String selectedItem = ureq.getParameter("item");
             event = new QTIWorksAssessmentTestEvent(selectItem, selectedItem, this);
             getRootForm().fireFormEvent(ureq, event);
             component.setDirty(true);
             testComponent.setDirty(true);
             break;
           }
         case mark:
           {
             String selectedItem = ureq.getParameter("item");
             event = new QTIWorksAssessmentTestEvent(mark, selectedItem, this);
             getRootForm().fireFormEvent(ureq, event);
             break;
           }
         default:
           break;
       }
     }
   }
 }
 @Override
 public boolean isSafelyAllowed(HttpServletRequest request, String safeExamBrowserKeys) {
   boolean safe = false;
   boolean debug = log.isDebug();
   if (StringHelper.containsNonWhitespace(safeExamBrowserKeys)) {
     String safeExamHash = request.getHeader("x-safeexambrowser-requesthash");
     String url = request.getRequestURL().toString();
     for (StringTokenizer tokenizer = new StringTokenizer(safeExamBrowserKeys);
         tokenizer.hasMoreTokens() && !safe; ) {
       String safeExamBrowserKey = tokenizer.nextToken();
       String hash = Encoder.sha256Exam(url + safeExamBrowserKey);
       if (safeExamHash != null && safeExamHash.equals(hash)) {
         safe = true;
       }
       if (debug) {
         log.debug(
             (safeExamHash.equals(hash) ? "Success" : "Failed")
                 + " : "
                 + safeExamHash
                 + " (Header) "
                 + hash
                 + " (Calculated)");
       }
     }
   } else {
     safe = true;
   }
   return safe;
 }
  @Override
  protected boolean validateFormLogic(UserRequest ureq) {
    String searchValue = search.getValue();

    if (isUsedInStepWizzard()) {
      return true;
    }
    if ((lastSearchValue == null && StringHelper.containsNonWhitespace(searchValue))
        || (lastSearchValue != null && !lastSearchValue.equals(searchValue))) {
      // User pressed enter in input field to search for groups, no group
      // selected yet. Just search for groups that matches for this input
      doSearchGroups(searchValue, ureq);
      lastSearchValue = searchValue;
      return false;
    }
    errorComp.clearError();
    boolean result = false;
    List<Long> ownerGroups = getCheckedTutorKeys();
    List<Long> partGroups = getCheckedParticipantKeys();
    result = (ownerGroups.size() > 0 || partGroups.size() > 0);
    if (!result) {
      errorComp.setErrorKey("error.choose.one", null);
    }
    return result;
  }
 public void setElementCSSClass(String cssClass) {
   if (StringHelper.containsNonWhitespace(cssClass)) {
     wrapper.contextPut("cssClass", cssClass);
   } else {
     wrapper.contextRemove("cssClass");
   }
 }
Esempio n. 14
0
  private void commitFields() {
    for (SliderRow row : sliders) {
      String start = row.getStartLabelEl().getValue();
      String end = row.getEndLabelEl().getValue();

      if (StringHelper.containsNonWhitespace(start)) {
        row.getSlider().setStartLabel(start);
      } else {
        row.getSlider().setStartLabel(null);
      }
      if (StringHelper.containsNonWhitespace(end)) {
        row.getSlider().setEndLabel(end);
      } else {
        row.getSlider().setEndLabel(null);
      }
    }
  }
 /** @return */
 public Integer getGroupMin() {
   String result = businessGroupMinimumMembers.getValue();
   if (StringHelper.containsNonWhitespace(result)) {
     result = result.replaceAll(" ", "");
     return Integer.parseInt(result);
   } else {
     return null;
   }
 }
 /**
  * Returns the CSV Header line containing all property names in the exact same way as in the
  * config file - excluding those properties which could not be retrieved, i.e. for which no
  * PropertyDescriptor could be created
  *
  * @return the CSV Header line containing all property names in the exact same way as in the
  *     config file - excluding those properties which could not be retrieved, i.e. for which no
  *     PropertyDescriptor could be created
  */
 public String getCSVHeader() {
   List<String> propertyNames = new ArrayList<String>();
   for (Iterator<PropertyDescriptor> it = orderedExportedPropertyDescriptors.iterator();
       it.hasNext(); ) {
     PropertyDescriptor pd = it.next();
     propertyNames.add(pd.getName());
   }
   return StringHelper.formatAsCSVString(propertyNames);
 }
Esempio n. 17
0
  /**
   * @param ureq
   * @return
   */
  private StringBuilder createChangelogMsg(UserRequest ureq) {
    /*
     * TODO:pb:is ImsRepositoryResolver the right place for getting the change log?
     */

    // re could be null, but if we are here it should not be null!
    Roles userRoles = ureq.getUserSession().getRoles();
    boolean showAll = userRoles.isAuthor() || userRoles.isOLATAdmin();
    // get changelog
    Formatter formatter = Formatter.getInstance(ureq.getLocale());
    ImsRepositoryResolver resolver = new ImsRepositoryResolver(referenceTestEntry);
    QTIChangeLogMessage[] qtiChangeLog = resolver.getDocumentChangeLog();
    StringBuilder qtiChangelog = new StringBuilder();

    if (qtiChangeLog.length > 0) {
      // there are resource changes
      Arrays.sort(qtiChangeLog);
      for (int i = qtiChangeLog.length - 1; i >= 0; i--) {
        // show latest change first
        if (!showAll && qtiChangeLog[i].isPublic()) {
          // logged in person is a normal user, hence public messages only
          Date msgDate = new Date(qtiChangeLog[i].getTimestmp());
          qtiChangelog
              .append("\nChange date: ")
              .append(formatter.formatDateAndTime(msgDate))
              .append("\n");
          String msg = StringHelper.escapeHtml(qtiChangeLog[i].getLogMessage());
          qtiChangelog.append(msg);
          qtiChangelog.append("\n********************************\n");
        } else if (showAll) {
          // logged in person is an author, olat admin, owner, show all messages
          Date msgDate = new Date(qtiChangeLog[i].getTimestmp());
          qtiChangelog
              .append("\nChange date: ")
              .append(formatter.formatDateAndTime(msgDate))
              .append("\n");
          String msg = StringHelper.escapeHtml(qtiChangeLog[i].getLogMessage());
          qtiChangelog.append(msg);
          qtiChangelog.append("\n********************************\n");
        } // else non public messages are not shown to normal user
      }
    }
    return qtiChangelog;
  }
Esempio n. 18
0
 private void launch(UserRequest ureq, String businessPath) {
   if (StringHelper.containsNonWhitespace(businessPath)) {
     try {
       // make the resume secure. If something fail, don't generate a red screen
       NewControllerFactory.getInstance().launch(businessPath, ureq, getWindowControl());
     } catch (Exception e) {
       logError("Error while resuming", e);
     }
   }
 }
 @Override
 public boolean isThumbnailPossible(VFSLeaf file) {
   String extension = FileUtils.getFileSuffix(file.getName());
   if (StringHelper.containsNonWhitespace(extension)) {
     for (ThumbnailSPI thumbnailSPI : thumbnailSPIes) {
       if (thumbnailSPI.getExtensions().contains(extension)) {
         return true;
       }
     }
   }
   return false;
 }
Esempio n. 20
0
 public String getCharacterDataFromElement(Node parentNode) {
   StringBuilder sb = new StringBuilder();
   for (Node node = parentNode.getFirstChild(); node != null; node = node.getNextSibling()) {
     if (node.getNodeType() == Node.TEXT_NODE) {
       String text = node.getNodeValue();
       if (StringHelper.containsNonWhitespace(text)) {
         sb.append(text);
       }
     }
   }
   return sb.toString();
 }
Esempio n. 21
0
 private void cleanup() {
   if (StringHelper.containsNonWhitespace(datas.getDataBackupFile())) {
     OlatRootFileImpl backupFile = new OlatRootFileImpl(datas.getDataBackupFile(), null);
     if (backupFile.exists()) {
       File dir = backupFile.getBasefile().getParentFile();
       if (dir != null && dir.exists()) {
         FileUtils.deleteDirsAndFiles(dir, true, true);
       }
     }
   }
   cleanupUnzip();
 }
 public static boolean isPaged(HttpServletRequest httpRequest, Request request) {
   String accept = httpRequest.getHeader("Accept");
   if (StringHelper.containsNonWhitespace(accept)) {
     MediaType requestMediaType = MediaType.valueOf(accept);
     if (APPLICATION_JSON_PAGED.equals(requestMediaType)
         || APPLICATION_XML_PAGED.equals(requestMediaType)) {
       return true;
     }
   }
   Variant variant = request.selectVariant(variants);
   return (variant != null
       && (variant.equals(APPLICATION_JSON_PAGED) || variant.equals(APPLICATION_XML_PAGED)));
 }
  private void updateGUI(ModelInfos modelInfos) {
    if (modelInfos.isSame()) {
      applyToAllEl.select(onKeys[0], true);
      table.setVisible(false);

      if (groupPassedEl != null) {
        groupPassedEl.setVisible(true);
        Boolean passed = modelInfos.getPassed();
        groupPassedEl.select(onKeys[0], passed != null && passed.booleanValue());
      }
      if (groupScoreEl != null) {
        groupScoreEl.setVisible(true);
        Float score = modelInfos.getScore();
        if (score != null) {
          String scoreVal = AssessmentHelper.getRoundedScore(score);
          groupScoreEl.setValue(scoreVal);
        } else {
          groupScoreEl.setValue("");
        }
      }
      if (groupCommentEl != null) {
        groupCommentEl.setVisible(true);
        String comment = modelInfos.getComment();
        if (comment != null) {
          groupCommentEl.setValue(comment);
        }
      }
    } else {
      applyToAllEl.select(onKeys[0], false);
      table.setVisible(true);
      if (groupPassedEl != null) {
        groupPassedEl.setVisible(false);
      }
      if (groupScoreEl != null) {
        groupScoreEl.setVisible(false);
      }
      if (groupCommentEl != null) {
        groupCommentEl.setVisible(false);
      }
    }

    if (StringHelper.containsNonWhitespace(modelInfos.getDuplicates())) {
      String warning =
          translate(
              "error.duplicate.memberships",
              new String[] {gtaNode.getShortTitle(), modelInfos.getDuplicates()});
      flc.contextPut("duplicateWarning", warning);
    } else {
      flc.contextRemove("duplicateWarning");
    }
  }
Esempio n. 24
0
  private void exposeUserTestDataToVC(UserRequest ureq) {
    // config : show score info
    Object enableScoreInfoObject = modConfig.get(IQEditController.CONFIG_KEY_ENABLESCOREINFO);
    if (enableScoreInfoObject != null) {
      myContent.contextPut("enableScoreInfo", enableScoreInfoObject);
    } else {
      myContent.contextPut("enableScoreInfo", Boolean.TRUE);
    }
    // configuration data
    myContent.contextPut("attemptsConfig", modConfig.get(IQEditController.CONFIG_KEY_ATTEMPTS));

    // user data
    Identity identity = userCourseEnv.getIdentityEnvironment().getIdentity();
    if (courseNode instanceof PersistentAssessableCourseNode) {
      PersistentAssessableCourseNode acn = (PersistentAssessableCourseNode) courseNode;
      AssessmentEntry assessmentEntry = acn.getUserAssessmentEntry(userCourseEnv);
      if (assessmentEntry == null) {
        myContent.contextPut("blockAfterSuccess", Boolean.FALSE);
        myContent.contextPut("score", null);
        myContent.contextPut("hasPassedValue", Boolean.FALSE);
        myContent.contextPut("passed", Boolean.FALSE);
        myContent.contextPut("comment", null);
        myContent.contextPut("attempts", 0);
      } else {
        // block if test passed (and config set to check it)
        Boolean blockAfterSuccess =
            modConfig.getBooleanEntry(IQEditController.CONFIG_KEY_BLOCK_AFTER_SUCCESS);
        Boolean blocked = Boolean.FALSE;
        if (blockAfterSuccess != null && blockAfterSuccess.booleanValue()) {
          Boolean passed = assessmentEntry.getPassed();
          if (passed != null && passed.booleanValue()) {
            blocked = Boolean.TRUE;
          }
        }
        myContent.contextPut("blockAfterSuccess", blocked);
        myContent.contextPut("score", AssessmentHelper.getRoundedScore(assessmentEntry.getScore()));
        myContent.contextPut(
            "hasPassedValue", (assessmentEntry.getPassed() == null ? Boolean.FALSE : Boolean.TRUE));
        myContent.contextPut("passed", assessmentEntry.getPassed());
        StringBuilder comment = Formatter.stripTabsAndReturns(assessmentEntry.getComment());
        myContent.contextPut("comment", StringHelper.xssScan(comment));
        myContent.contextPut("attempts", assessmentEntry.getAttempts());
      }
    }

    UserNodeAuditManager am = userCourseEnv.getCourseEnvironment().getAuditManager();
    myContent.contextPut("log", am.getUserNodeLog(courseNode, identity));

    exposeResults(ureq);
  }
Esempio n. 25
0
 private void render(StringOutput sb, MemberView member) {
   List<BusinessGroupShort> groups = member.getGroups();
   if (groups != null && !groups.isEmpty()) {
     boolean and = false;
     for (BusinessGroupShort group : groups) {
       and = and(sb, and);
       if (group.getName() == null) {
         sb.append(group.getKey());
       } else {
         sb.append(StringHelper.escapeHtml(group.getName()));
       }
     }
   }
 }
 private String getResponseSummary(Response response) {
   String responseSummary;
   if (response.getContent() == null) {
     responseSummary = null;
   } else {
     responseSummary = response.getContent().renderAsText();
     if (responseSummary.length() > 128) {
       responseSummary = new NekoHTMLFilter().filter(responseSummary);
       if (responseSummary.length() > 128) {
         responseSummary = responseSummary.substring(0, 125) + "...";
       }
     }
   }
   return StringHelper.containsNonWhitespace(responseSummary) ? responseSummary : null;
 }
    public String getInfos() {
      if (infos == null && link.getOffer() != null) {
        OfferImpl casted = (OfferImpl) link.getOffer();
        if (StringHelper.containsNonWhitespace(casted.getToken())) {
          return casted.getToken();
        }
        if (!link.getOffer().getPrice().isEmpty()) {
          String price = PriceFormat.fullFormat(link.getOffer().getPrice());
          if (acModule.isVatEnabled()) {
            BigDecimal vat = acModule.getVat();
            String vatStr =
                vat == null ? "" : vat.setScale(3, BigDecimal.ROUND_HALF_EVEN).toPlainString();
            return translate("access.info.price.vat", new String[] {price, vatStr});

          } else {
            return translate("access.info.price.noVat", new String[] {price});
          }
        }
      }
      if (StringHelper.containsNonWhitespace(infos)) {
        return infos;
      }
      return "";
    }
 /**
  * [used by Spring]
  *
  * @param cronExpression
  */
 public void setCronExpression(String cronExpression) {
   if (CronExpression.isValidExpression(cronExpression)) {
     this.cronExpression = cronExpression;
   } else {
     if (StringHelper.containsNonWhitespace(cronExpression)) {
       // was not empty, so someone tried to set someting here, let user know that it was garbage
       log.warn(
           "Configured cron expression is not valid::"
               + cronExpression
               + " check your search.indexing.cronjob.expression property",
           null);
     }
     this.cronExpression = null;
   }
 }
 @Override
 protected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) {
   if (selectLink == source) {
     Set<Integer> selections = getItemsTable().getMultiSelectedIndex();
     if (!selections.isEmpty()) {
       List<QuestionItemView> items = getItemViews(selections);
       fireEvent(ureq, new QItemViewEvent("select-item", items));
     }
   } else if (myListEl == source) {
     String selectedCollKey = myListEl.getSelectedKey();
     if (StringHelper.isLong(selectedCollKey)) {
       Long collectionKey = Long.parseLong(selectedCollKey);
       doSelectCollection(ureq, collectionKey);
     }
   }
   super.formInnerEvent(ureq, source, event);
 }
Esempio n. 30
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();
  }