Example usage for org.apache.commons.math.util MathUtils equalsIncludingNaN

List of usage examples for org.apache.commons.math.util MathUtils equalsIncludingNaN

Introduction

In this page you can find the example usage for org.apache.commons.math.util MathUtils equalsIncludingNaN.

Prototype

public static boolean equalsIncludingNaN(double x, double y, int maxUlps) 

Source Link

Document

Returns true if both arguments are NaN or if they are equal as defined by #equals(double,double,int) equals(x, y, maxUlps .

Usage

From source file:org.sakaiproject.tool.assessment.services.GradingService.java

public void notifyGradebook(AssessmentGradingData data, PublishedAssessmentIfc pub)
        throws GradebookServiceException {
    // If the assessment is published to the gradebook, make sure to update the scores in the gradebook
    String toGradebook = pub.getEvaluationModel().getToGradeBook();

    GradebookExternalAssessmentService g = null;
    boolean integrated = IntegrationContextFactory.getInstance().isIntegrated();
    if (integrated) {
        g = (GradebookExternalAssessmentService) SpringBeanLocator.getInstance()
                .getBean("org.sakaiproject.service.gradebook.GradebookExternalAssessmentService");
    }/*  w  w  w .  j a v  a  2s  .c o  m*/

    GradebookServiceHelper gbsHelper = IntegrationContextFactory.getInstance().getGradebookServiceHelper();

    PublishedAssessmentService publishedAssessmentService = new PublishedAssessmentService();
    String currentSiteId = publishedAssessmentService
            .getPublishedAssessmentSiteId(pub.getPublishedAssessmentId().toString());
    if (gbsHelper.gradebookExists(GradebookFacade.getGradebookUId(currentSiteId), g)
            && toGradebook.equals(EvaluationModelIfc.TO_DEFAULT_GRADEBOOK.toString())) {
        if (log.isDebugEnabled())
            log.debug("Attempting to update a score in the gradebook");

        // add retry logic to resolve deadlock problem while sending grades to gradebook

        Double originalFinalScore = data.getFinalScore();
        int retryCount = PersistenceService.getInstance().getPersistenceHelper().getRetryCount().intValue();
        while (retryCount > 0) {
            try {
                // Send the average score if average was selected for multiple submissions
                Integer scoringType = pub.getEvaluationModel().getScoringType();
                if (scoringType.equals(EvaluationModelIfc.AVERAGE_SCORE)) {
                    // status = 5: there is no submission but grader update something in the score page
                    if (data.getStatus() == 5) {
                        data.setFinalScore(data.getFinalScore());
                    } else {
                        Double averageScore = PersistenceService.getInstance()
                                .getAssessmentGradingFacadeQueries().getAverageSubmittedAssessmentGrading(
                                        Long.valueOf(pub.getPublishedAssessmentId()), data.getAgentId());
                        data.setFinalScore(averageScore);
                    }
                }
                gbsHelper.updateExternalAssessmentScore(data, g);
                retryCount = 0;
            } catch (org.sakaiproject.service.gradebook.shared.AssessmentNotFoundException ante) {
                log.warn("problem sending grades to gradebook: " + ante.getMessage());
                if (AssessmentIfc.RETRACT_FOR_EDIT_STATUS.equals(pub.getStatus())) {
                    retryCount = retry(retryCount, ante, pub, true);
                } else {
                    // Otherwise, do the same exeption handling as others
                    retryCount = retry(retryCount, ante, pub, false);
                }
            } catch (Exception e) {
                retryCount = retry(retryCount, e, pub, false);
            }
        }

        // change the final score back to the original score since it may set to average score.
        // data.getFinalScore() != originalFinalScore
        if (!(MathUtils.equalsIncludingNaN(data.getFinalScore(), originalFinalScore, 0.0001))) {
            data.setFinalScore(originalFinalScore);
        }

        try {
            Long publishedAssessmentId = data.getPublishedAssessmentId();
            String agent = data.getAgentId();
            String comment = data.getComments();
            gbsHelper.updateExternalAssessmentComment(publishedAssessmentId, agent, comment, g);
        } catch (Exception ex) {
            log.warn("Error sending comments to gradebook: " + ex.getMessage());
        }
    } else {
        if (log.isDebugEnabled())
            log.debug("Not updating the gradebook.  toGradebook = " + toGradebook);
    }
}

From source file:org.sakaiproject.tool.assessment.ui.listener.delivery.DeliveryActionListener.java

/**
 * populate a single ItemContentsBean from an item for delivery
 * @param item  an Item/*w  w  w .j a va 2  s  .  c  o m*/
 * @return
 */
private ItemContentsBean getQuestionBean(ItemDataIfc item, HashMap itemGradingHash, DeliveryBean delivery,
        HashMap publishedAnswerHash) {
    ItemContentsBean itemBean = new ItemContentsBean();
    itemBean.setItemData(item);
    itemBean.setMaxPoints(item.getScore().doubleValue());
    itemBean.setPoints((double) 0);

    // update maxNumAttempts for audio
    if (item.getTriesAllowed() != null) {
        itemBean.setTriesAllowed(item.getTriesAllowed());
    }

    // save timeallowed for audio recording
    if (item.getDuration() != null) {
        itemBean.setDuration(item.getDuration());
    }

    itemBean.setItemGradingDataArray((ArrayList) itemGradingHash.get(item.getItemId()));

    if (itemBean.getItemGradingDataArray().size() > 0) {
        itemBean.setItemGradingIdForFilePicker(
                ((ItemGradingData) itemBean.getItemGradingDataArray().get(0)).getItemGradingId());
    }
    // Set comments and points
    Iterator i = itemBean.getItemGradingDataArray().iterator();
    ArrayList itemGradingAttachmentList = new ArrayList();
    while (i.hasNext()) {
        ItemGradingData data = (ItemGradingData) i.next();
        // All itemgradingdata comments for the same item are identical <- u sure? daisyf
        itemBean.setGradingComment(data.getComments());
        if (data.getAutoScore() != null) {
            itemBean.setPoints(itemBean.getExactPoints() + data.getAutoScore().doubleValue());
        }
        // set attempts remaining for audio, there is only one itemGradingData
        // per question in this case  
        if (data.getAttemptsRemaining() != null) {
            itemBean.setAttemptsRemaining(data.getAttemptsRemaining());
        }

        // set the itemGradingAttachment only for Review and Grading flows because itemGradingAttachment 
        // can exist in these two flows only (grader can only enter comments for submitted assessments) 
        if (delivery.getActionMode() == 3 || delivery.getActionMode() == 4) {
            itemGradingAttachmentList.addAll(data.getItemGradingAttachmentList());
        } else {
            itemGradingAttachmentList.addAll(new ArrayList<ItemGradingAttachment>());
        }
        //itemBean.setItemGradingAttachmentList(data.getItemGradingAttachmentList());
    }

    //If the value close enough to the maximum value just set it to the maximum value (precision issue)
    if (MathUtils.equalsIncludingNaN(itemBean.getExactPoints(), itemBean.getMaxPoints(), 0.001d)) {
        itemBean.setPoints(itemBean.getMaxPoints());
    }

    itemBean.setItemGradingAttachmentList(itemGradingAttachmentList);

    // set question feedback.
    if (item.getTypeId().equals(TypeIfc.ESSAY_QUESTION) || item.getTypeId().equals(TypeIfc.FILE_UPLOAD)
            || item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY)
            || item.getTypeId().equals(TypeIfc.AUDIO_RECORDING)
            || item.getTypeId().equals(TypeIfc.MATRIX_CHOICES_SURVEY))

    {
        itemBean.setFeedback(item.getGeneralItemFeedback());
    }

    else if (itemBean.getMaxPoints() > 0 && !item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT)) {
        // 
        // This is not really needed because the next Else{} will cover all other question types. 
        // However it's much cheaper to check scores rather than looping through and check each answers. 
        // I'm keeping it here.  In most cases, this condition will be met. 

        if (itemBean.getExactPoints() >= itemBean.getMaxPoints()) {

            itemBean.setFeedback(item.getCorrectItemFeedback());
        } else {
            itemBean.setFeedback(item.getInCorrectItemFeedback());
        }
    } else {
        // run this check if the question is worth 0 points.  see SAK-5669
        // In this case, we can't just check the scores to determine which feedback to show.
        // this doesn't happen very often. 

        List<ItemGradingData> itemgradingList = itemBean.getItemGradingDataArray();
        Iterator<ItemGradingData> iterAnswer = itemgradingList.iterator();
        boolean haswronganswer = true;
        HashMap fibmap = new HashMap();
        int mcmc_match_counter = 0;
        // if no answers yet, then display incorrect feedback. 
        // if there are answers, then initialize haswronganswer =false;  // correct feedback
        if (iterAnswer.hasNext()) {
            haswronganswer = false;
        }

        //calculate total # of correct answers. 
        int correctAnswers = 0;
        if ((item.getTypeId().equals(TypeIfc.EXTENDED_MATCHING_ITEMS))
                || (item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT))
                || (item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION))
                || (item.getTypeId().equals(TypeIfc.MATCHING))) {
            Iterator itemTextIter = item.getItemTextArray().iterator();
            while (itemTextIter.hasNext()) {
                ItemTextIfc itemText = (ItemTextIfc) itemTextIter.next();
                List answerArray = itemText.getAnswerArray();

                if (answerArray != null) {
                    for (int indexAnswer = 0; indexAnswer < answerArray.size(); indexAnswer++) {
                        AnswerIfc a = (AnswerIfc) answerArray.get(indexAnswer);
                        if (a.getIsCorrect().booleanValue())
                            correctAnswers++;
                    }
                }
            }
        }
        //log.debug("correctAnswers: " + correctAnswers);

        //check if there's wrong answer in the answer list, matrix survey question won't affect it, since the answer is always right, 
        //so don't need to check the matrix survey question
        while (iterAnswer.hasNext()) {

            ItemGradingData data = iterAnswer.next();

            AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId());

            if (item.getTypeId().equals(TypeIfc.FILL_IN_BLANK)) {
                GradingService gs = new GradingService();
                boolean correctanswer = gs.getFIBResult(data, fibmap, item, publishedAnswerHash);
                if (!correctanswer) {
                    haswronganswer = true;
                    break;
                }

            } else if (item.getTypeId().equals(TypeIfc.FILL_IN_NUMERIC)) {
                GradingService gs = new GradingService();
                try {
                    boolean correctanswer = gs.getFINResult(data, item, publishedAnswerHash);
                    if (!correctanswer) {
                        haswronganswer = true;
                        break;
                    }
                } catch (FormatException e) {
                    log.debug("should not come to here");
                }
            } else if ((item.getTypeId().equals(TypeIfc.EXTENDED_MATCHING_ITEMS))
                    || (item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT))
                    || (item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION))
                    || (item.getTypeId().equals(TypeIfc.MATCHING))) {
                if ((answer != null)
                        && (answer.getIsCorrect() == null || !answer.getIsCorrect().booleanValue())) {
                    haswronganswer = true;

                    break;
                } else if (answer != null) {
                    // for matching, if no selection has been made, answer = null.  
                    //we don't want to increment mcmc_match_counter if answer is null
                    mcmc_match_counter++;
                }
            } else {
                // for other question types, tf, mcsc, mcmc and matching
                if ((answer != null)
                        && (answer.getIsCorrect() == null || !answer.getIsCorrect().booleanValue())) {
                    haswronganswer = true;
                    break;
                }
            }

        }
        if ((item.getTypeId().equals(TypeIfc.EXTENDED_MATCHING_ITEMS))
                || (item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT))
                || (item.getTypeId().equals(TypeIfc.MATCHING))) {
            if (mcmc_match_counter == correctAnswers) {
                haswronganswer = false;
            } else {
                haswronganswer = true;
            }
        }

        if (haswronganswer) {
            itemBean.setFeedback(item.getInCorrectItemFeedback());
        } else {

            itemBean.setFeedback(item.getCorrectItemFeedback());
        }

    }

    // Do we randomize answer list?

    boolean randomize = false;
    i = item.getItemMetaDataSet().iterator();
    while (i.hasNext()) {
        ItemMetaDataIfc meta = (ItemMetaDataIfc) i.next();
        if (meta.getLabel().equals(ItemMetaDataIfc.RANDOMIZE)) {
            if (meta.getEntry().equals("true")) {
                randomize = true;
                break;
            }
        }
    }

    ArrayList myanswers = new ArrayList();
    ResourceLoader rb = null;
    rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.DeliveryMessages");

    // Generate the answer key
    String key = "";
    Iterator key1 = item.getItemTextArraySorted().iterator();
    int j = 0;
    while (key1.hasNext()) {
        j++;
        // We need to store the answers in an arraylist in case they're
        // randomized -- we assign labels here, and then step through
        // them again later, and we have to make sure the order is the
        // same each time.
        myanswers = new ArrayList(); // Start over each time so we don't
        // get duplicates.
        ItemTextIfc text = (ItemTextIfc) key1.next();
        Iterator key2 = null;

        if (item.getTypeId().equals(TypeIfc.EXTENDED_MATCHING_ITEMS) && text.isEmiQuestionItemText()) {
            //changes for VULA-1861 - EMI answer key format in delivery is confusing
            int correctAnswerCnt = 0;
            Iterator answersIter = text.getAnswerArraySorted().iterator();
            while (answersIter.hasNext()) {
                AnswerIfc answer = (AnswerIfc) answersIter.next();
                if (answer.getIsCorrect()) {
                    correctAnswerCnt += 1;
                }
            }
            String required = null;
            if (text.getRequiredOptionsCount() != null
                    && text.getRequiredOptionsCount().intValue() < correctAnswerCnt) {
                required = text.getRequiredOptionsCount().toString();
                key += " | " + text.getSequence() + ": " + required + " " + rb.getString("of") + " ";
            } else {
                key += " | " + text.getSequence() + ": ";
            }
        }

        List<Long> alwaysRandomizeTypes = Arrays.asList(TypeIfc.MATCHING);
        List<Long> neverRandomizeTypes = Arrays.asList(TypeIfc.FILL_IN_BLANK, TypeIfc.FILL_IN_NUMERIC,
                TypeIfc.MATRIX_CHOICES_SURVEY, TypeIfc.CALCULATED_QUESTION, TypeIfc.IMAGEMAP_QUESTION);

        if (alwaysRandomizeTypes.contains(item.getTypeId())
                || (randomize && !neverRandomizeTypes.contains(item.getTypeId()))) {
            ArrayList shuffled = new ArrayList();
            Iterator i1 = text.getAnswerArraySorted().iterator();
            while (i1.hasNext())

            {
                shuffled.add(i1.next());

                // Randomize matching the same way for each
            }

            // Show the answers in the same order that student did.
            String agentString = "";
            if (delivery.getActionMode() == DeliveryBean.GRADE_ASSESSMENT) {
                StudentScoresBean studentscorebean = (StudentScoresBean) ContextUtil
                        .lookupBean("studentScores");
                agentString = studentscorebean.getStudentId();
            } else {
                agentString = getAgentString();
            }

            String itemText = (item.getText() == null) ? "" : item.getText();
            Collections.shuffle(shuffled, new Random((long) itemText.hashCode()
                    + (getAgentString() + "_" + item.getItemId().toString()).hashCode()));
            /*
            if (item.getTypeId().equals(TypeIfc.MATCHING))
            {
              Collections.shuffle(shuffled,
                      new Random( (long) item.getText().hashCode() +
                    getAgentString().hashCode()));
            }
            else
            {
              Collections.shuffle(shuffled,
                      new Random( (long) item.getText().hashCode() +
                                 getAgentString().hashCode()));
            }
            */
            key2 = shuffled.iterator();
        } else {
            key2 = text.getAnswerArraySorted().iterator();
        }
        int k = 0;
        while (key2.hasNext()) {
            AnswerIfc answer = (AnswerIfc) key2.next();

            // Don't save the answer if it has no text
            if ((answer.getText() == null || answer.getText().trim().equals(""))
                    && (item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE)
                            || item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT)
                            || item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION)
                            || item.getTypeId().equals(TypeIfc.EXTENDED_MATCHING_ITEMS)
                            || item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY)
                            || item.getTypeId().equals(TypeIfc.MATRIX_CHOICES_SURVEY))) {
                // Ignore, it's a null answer
            } else {
                // Set the label and key
                if ((!item.getPartialCreditFlag() && item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE))
                        || item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT)
                        || item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION)
                        || item.getTypeId().equals(TypeIfc.MATCHING)
                        || item.getTypeId().equals(TypeIfc.IMAGEMAP_QUESTION)) {
                    answer.setLabel(Character.toString(alphabet.charAt(k++)));
                    if (answer.getIsCorrect() != null && answer.getIsCorrect().booleanValue()) {
                        String addition = "";
                        if (item.getTypeId().equals(TypeIfc.MATCHING)) {
                            addition = Integer.toString(j) + ":";
                        }

                        if ("".equals(key)) {
                            key += addition + answer.getLabel();
                        } else {
                            key += ", " + addition + answer.getLabel();
                        }
                    }
                }

                if (item.getTypeId().equals(TypeIfc.EXTENDED_MATCHING_ITEMS) && text.isEmiQuestionItemText()
                        && answer.getIsCorrect()) {
                    key += answer.getLabel();
                }

                //multiple choice partial credit:
                if (item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE) && item.getPartialCreditFlag()) {
                    Double pc = Double.valueOf(answer.getPartialCredit());
                    if (pc == null) {
                        pc = Double.valueOf(0d);
                    }
                    if (pc > 0) {
                        if (rb == null) {
                            rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.DeliveryMessages");
                        }
                        String correct = rb.getString("alt_correct");
                        if (("").equals(key)) {
                            key = answer.getLabel() + "&nbsp;<span style='color: green'>(" + pc + "%&nbsp;"
                                    + correct + ")</span>";
                        } else {
                            key += ",&nbsp;" + answer.getLabel() + "&nbsp;<span style='color: green'>(" + pc
                                    + "%&nbsp;" + correct + ")</span>";
                        }
                    }
                }

                if (item.getTypeId().equals(TypeIfc.TRUE_FALSE) && answer.getIsCorrect() != null
                        && answer.getIsCorrect().booleanValue()) {
                    if (rb == null) {
                        rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.DeliveryMessages");
                    }
                    if (answer.getText().equalsIgnoreCase("true")
                            || answer.getText().equalsIgnoreCase(rb.getString("true_msg"))) {
                        key = rb.getString("true_msg");
                    } else {
                        key = rb.getString("false_msg");
                    }
                }
                if (item.getTypeId().equals(TypeIfc.FILE_UPLOAD)
                        || item.getTypeId().equals(TypeIfc.ESSAY_QUESTION)
                        || item.getTypeId().equals(TypeIfc.AUDIO_RECORDING)) {
                    key += answer.getText();
                }
                if (item.getTypeId().equals(TypeIfc.FILL_IN_BLANK)
                        || item.getTypeId().equals(TypeIfc.FILL_IN_NUMERIC)) {
                    if ("".equals(key)) {
                        key += answer.getText();
                    } else {
                        key += ", " + answer.getText();
                    }
                }
                // CALCULATED_QUESTION
                if (item.getTypeId().equals(TypeIfc.CALCULATED_QUESTION)) {
                    key = commaDelimtedCalcQuestionAnswers(item, delivery, itemBean);
                }
                //myanswers will get the answer even for matrix and multiple choices survey
                myanswers.add(answer);
            }
        }
    }

    if (item.getTypeId().equals(TypeIfc.EXTENDED_MATCHING_ITEMS)) {
        key += " | ";
    }

    itemBean.setKey(key);

    // Delete this
    itemBean.setShuffledAnswers(myanswers);

    // This creates the list of answers for an item
    ArrayList answers = new ArrayList();
    if (item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE) || item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT)
            || item.getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION)
            || item.getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY)
            || item.getTypeId().equals(TypeIfc.TRUE_FALSE) || item.getTypeId().equals(TypeIfc.MATCHING)) {
        Iterator iter = myanswers.iterator();
        SelectionBean selectionBean = null;

        while (iter.hasNext()) {
            AnswerIfc answer = (AnswerIfc) iter.next();
            selectionBean = new SelectionBean();
            selectionBean.setItemContentsBean(itemBean);
            selectionBean.setAnswer(answer);

            // It's saved lower case in the db -- this is a kludge
            if (item.getTypeId().equals(TypeIfc.TRUE_FALSE) && // True/False
                    answer.getText().equals("true")) {
                if (rb == null) {
                    rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.DeliveryMessages");
                }
                answer.setText(rb.getString("true_msg"));
            }
            if (item.getTypeId().equals(TypeIfc.TRUE_FALSE) && // True/False
                    answer.getText().equals("false")) {
                if (rb == null) {
                    rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.DeliveryMessages");
                }
                answer.setText(rb.getString("false_msg"));

            }
            String label = "";
            if (answer.getLabel() == null) {
                answer.setLabel("");

                // Delete this when everything works.
            }
            if (!answer.getLabel().equals("")) {
                label += answer.getLabel() + ". " + answer.getText();
            } else {
                label = answer.getText();

                // Set the response to true or false for each answer
            }
            selectionBean.setResponse(false); // do this for each answer of choice, why?
            Iterator iter1 = itemBean.getItemGradingDataArray().iterator();
            while (iter1.hasNext()) {
                ItemGradingData data = (ItemGradingData) iter1.next();
                AnswerIfc pubAnswer = (AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId());
                if (pubAnswer != null
                        && (pubAnswer.equals(answer) || data.getPublishedAnswerId().equals(answer.getId()))) {
                    selectionBean.setItemGradingData(data);
                    selectionBean.setResponse(true); //<-- is this redundant?
                }
            }

            if (delivery.getFeedbackComponent() != null && delivery.getFeedback().equals("true")
                    && delivery.getFeedbackComponent().getShowSelectionLevel()) {
                // If right answer, set feedback to correct, otherwise incorrect
                if (answer.getIsCorrect() == null) {
                    selectionBean.setFeedback(answer.getGeneralAnswerFeedback());
                } else if (selectionBean.getResponse() && answer.getIsCorrect().booleanValue()
                        || !selectionBean.getResponse() && !answer.getIsCorrect().booleanValue()) {
                    selectionBean.setFeedback(answer.getCorrectAnswerFeedback());
                } else {
                    selectionBean.setFeedback(answer.getInCorrectAnswerFeedback());

                }
            }

            // Delete this
            String description = "";
            if (delivery.getFeedback().equals("true")
                    && delivery.getFeedbackComponent().getShowCorrectResponse()
                    && answer.getIsCorrect() != null) {
                description = answer.getIsCorrect().toString();

                // Delete this
            }
            SelectItem newItem = new SelectItem(answer.getId().toString(), label, description);

            if (item.getTypeId().equals(TypeIfc.TRUE_FALSE)) {
                answers.add(newItem);
            } else {
                answers.add(selectionBean);
            }
        } //end while
    }
    // Delete this
    itemBean.setAnswers(answers);
    itemBean.setSelectionArray(answers);

    if (item.getTypeId().equals(TypeIfc.MATCHING)) // matching
    {
        populateMatching(item, itemBean, publishedAnswerHash);
    } else if (item.getTypeId().equals(TypeIfc.EXTENDED_MATCHING_ITEMS)) {
        populateEMI(item, itemBean, publishedAnswerHash);
    } else if (item.getTypeId().equals(TypeIfc.FILL_IN_BLANK)) // fill in the blank
    {
        populateFib(item, itemBean, publishedAnswerHash);
    } else if (item.getTypeId().equals(TypeIfc.FILL_IN_NUMERIC)) //numeric response
    {
        populateFin(item, itemBean, publishedAnswerHash);
    } else if (item.getTypeId().equals(TypeIfc.ESSAY_QUESTION)) {
        String responseText = itemBean.getResponseText();
        // SAK-17021
        // itemBean.setResponseText(FormattedText.convertFormattedTextToPlaintext(responseText));
        itemBean.setResponseText(ContextUtil.stringWYSIWYG(responseText));
    } else if (item.getTypeId().equals(TypeIfc.MATRIX_CHOICES_SURVEY)) {
        populateMatrixChoices(item, itemBean, publishedAnswerHash);
    }
    // CALCULATED_QUESTION
    else if (item.getTypeId().equals(TypeIfc.CALCULATED_QUESTION)) {
        populateCalculatedQuestion(item, itemBean, delivery);
    } else if (item.getTypeId().equals(TypeIfc.IMAGEMAP_QUESTION)) {
        populateImageMapQuestion(item, itemBean, publishedAnswerHash);
    }

    return itemBean;
}

From source file:org.sakaiproject.tool.assessment.ui.listener.evaluation.QuestionScoreUpdateListener.java

/**
 * Persist the results from the ActionForm in the question page.
 * @param bean QuestionScoresBean bean/*from  www. j ava2s .co m*/
 * @return true if successful
 */
public boolean saveQuestionScores(QuestionScoresBean bean, TotalScoresBean tbean) {
    try {
        GradingService delegate = new GradingService();
        //String publishedId = ContextUtil.lookupParam("publishedId");
        String itemId = ContextUtil.lookupParam("itemId");
        String which = ContextUtil.lookupParam("allSubmissions");
        if (which == null)
            which = "false";
        Collection agents = bean.getAgents();
        //ArrayList items = new ArrayList();
        Iterator iter = agents.iterator();
        while (iter.hasNext()) {
            // each agent has a list of modified itemGrading
            AgentResults ar = (AgentResults) iter.next();
            // Get the itemgradingdata list for this result
            ArrayList datas = (ArrayList) bean.getScoresByItem()
                    .get(ar.getAssessmentGradingId() + ":" + itemId);
            if (datas == null)
                datas = new ArrayList();

            int fibFinNumCorrect = 0;
            if (bean.getTypeId().equals("8") || bean.getTypeId().equals("11")) {
                Iterator iter1 = datas.iterator();
                while (iter1.hasNext()) {
                    Object obj = iter1.next();
                    ItemGradingData data = (ItemGradingData) obj;
                    if (data.getIsCorrect() != null && data.getIsCorrect().booleanValue()) {
                        fibFinNumCorrect++;
                    }
                }
            }

            boolean hasUpdateAttachment = false;
            Iterator iter2 = datas.iterator();
            while (iter2.hasNext()) {
                Object obj = iter2.next();
                //log.info("Data = " + obj);
                ItemGradingData data = (ItemGradingData) obj;

                // check if there is differnce in score, if so, update. Otherwise, do nothing
                double newAutoScore = 0;
                if ((bean.getTypeId().equals("8") || bean.getTypeId().equals("11")) && fibFinNumCorrect != 0) {
                    if (Boolean.TRUE.equals(data.getIsCorrect())) {
                        newAutoScore = (Double.valueOf(ar.getTotalAutoScore())).doubleValue()
                                / (double) fibFinNumCorrect;
                    }
                } else {
                    newAutoScore = (Double.valueOf(ar.getTotalAutoScore())).doubleValue()
                            / (double) datas.size();
                }
                String newComments = TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log,
                        ar.getComments());
                ar.setComments(newComments);
                if (newComments != null) {
                    newComments = newComments.trim();
                } else {
                    newComments = "";
                }

                double oldAutoScore = 0;
                if (data.getAutoScore() != null)
                    oldAutoScore = data.getAutoScore().doubleValue();

                String oldComments = data.getComments();
                if (oldComments != null) {
                    oldComments = oldComments.trim();
                } else {
                    oldComments = "";
                }

                StringBuffer logString = new StringBuffer();
                logString.append("gradedBy=");
                logString.append(AgentFacade.getAgentString());
                logString.append(", itemGradingId=");
                logString.append(data.getItemGradingId());

                // if newAutoScore != oldAutoScore
                if (!(MathUtils.equalsIncludingNaN(newAutoScore, oldAutoScore, 0.0001))) {
                    data.setAutoScore(Double.valueOf(newAutoScore));
                    logString.append(", newAutoScore=");
                    logString.append(newAutoScore);
                    logString.append(", oldAutoScore=");
                    logString.append(oldAutoScore);
                }
                if (!newComments.equals(oldComments)) {
                    data.setComments(ar.getComments());
                    logString.append(", newComments=");
                    logString.append(newComments);
                    logString.append(", oldComments=");
                    logString.append(oldComments);
                }

                // if newAutoScore != oldAutoScore or newComments != oldComments
                if (!(MathUtils.equalsIncludingNaN(newAutoScore, oldAutoScore, 0.0001))
                        || !newComments.equals(oldComments)) {
                    data.setGradedBy(AgentFacade.getAgentString());
                    data.setGradedDate(new Date());
                    String targetString = "siteId=" + AgentFacade.getCurrentSiteId() + ", "
                            + logString.toString();
                    String safeString = targetString.length() > 255 ? targetString.substring(0, 255)
                            : targetString;
                    EventTrackingService
                            .post(EventTrackingService.newEvent("sam.question.score.update", safeString, true));
                    delegate.updateItemScore(data, newAutoScore - oldAutoScore, tbean.getPublishedAssessment());
                }

                if (!hasUpdateAttachment) {
                    hasUpdateAttachment = true;
                    updateAttachment(data, ar, bean);
                }
            }
        }

    } catch (GradebookServiceException ge) {
        FacesContext context = FacesContext.getCurrentInstance();
        String err = (String) ContextUtil.getLocalizedString(
                "org.sakaiproject.tool.assessment.bundle.AuthorMessages", "gradebook_exception_error");
        context.addMessage(null, new FacesMessage(err));

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:org.sakaiproject.tool.assessment.ui.listener.evaluation.StudentScoreUpdateListener.java

/**
 * Persist the results from the ActionForm in the student page.
 * @param bean StudentScoresBean bean/*w ww .j a va 2  s .c  o  m*/
 * @return true if successful
 */
public boolean saveStudentScores(StudentScoresBean bean, TotalScoresBean tbean, DeliveryBean delivery) {
    GradingService delegate = new GradingService();
    HashSet itemGradingSet = new HashSet();
    AssessmentGradingData adata = null;
    try {
        ArrayList parts = delivery.getPageContents().getPartsContents();
        Iterator iter = parts.iterator();
        boolean updateFlag = false;
        while (iter.hasNext()) {
            ArrayList items = ((SectionContentsBean) iter.next()).getItemContents();
            Iterator iter2 = items.iterator();
            while (iter2.hasNext()) {
                ItemContentsBean question = (ItemContentsBean) iter2.next();
                List<ItemGradingData> gradingarray = question.getItemGradingDataArray();
                log.debug("****1. pub questionId = " + question.getItemData().getItemId());
                log.debug("****2. Gradingarray length = " + gradingarray.size());
                // Create a new one if we need it.
                if (gradingarray.isEmpty()
                        && (question.getExactPoints() > 0 || (question.getGradingComment() != null
                                && !question.getGradingComment().trim().equals("")))) {
                    // this is another mystery, no idea why review is involved here - daiyf
                    question.setReview(false); // This creates an itemgradingdata
                    gradingarray = question.getItemGradingDataArray();
                }

                int fibFinNumCorrect = 0;
                if (question.getItemData().getTypeId().equals(Long.valueOf(8))
                        || question.getItemData().getTypeId().equals(Long.valueOf(11))) {
                    Iterator itemGradingIter = gradingarray.iterator();
                    while (itemGradingIter.hasNext()) {
                        Object obj = itemGradingIter.next();
                        ItemGradingData data = (ItemGradingData) obj;
                        if (Boolean.TRUE.equals(data.getIsCorrect())) {
                            fibFinNumCorrect++;
                        }
                    }
                }

                log.debug("****3a Gradingarray length2 = " + gradingarray.size());
                log.debug("****3b set points = " + question.getExactPoints() + ", comments to "
                        + question.getGradingComment());
                Iterator iter3 = gradingarray.iterator();
                while (iter3.hasNext()) {
                    ItemGradingData data = (ItemGradingData) iter3.next();
                    if (adata == null && data.getAssessmentGradingId() != null) {
                        adata = delegate.load(data.getAssessmentGradingId().toString());
                    }
                    if (data.getAgentId() == null) { // this is a skipped question, set submittedDate=null
                        data.setSubmittedDate(null);
                        data.setAgentId(bean.getStudentId());
                    }

                    double newAutoScore = 0;
                    if ((question.getItemData().getTypeId().equals(Long.valueOf(8))
                            || question.getItemData().getTypeId().equals(Long.valueOf(11)))
                            && fibFinNumCorrect != 0) {
                        if (Boolean.TRUE.equals(data.getIsCorrect())) {
                            newAutoScore = (question.getExactPoints() / (double) fibFinNumCorrect);
                        }
                    } else {
                        newAutoScore = (question.getExactPoints() / (double) gradingarray.size());
                    }
                    double oldAutoScore = 0;
                    if (data.getAutoScore() != null) {
                        oldAutoScore = data.getAutoScore().doubleValue();
                    }
                    String newComments = TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log,
                            question.getGradingComment());
                    if (newComments != null) {
                        newComments = newComments.trim();
                    } else {
                        newComments = "";
                    }
                    String oldComments = data.getComments();
                    if (oldComments != null) {
                        oldComments = oldComments.trim();
                    } else {
                        oldComments = "";
                    }

                    // if newAutoScore != oldAutoScore then updateScore = true
                    boolean updateScore = !(MathUtils.equalsIncludingNaN(newAutoScore, oldAutoScore, 0.0001));
                    boolean updateComments = !newComments.equals(oldComments);
                    StringBuffer logString = new StringBuffer();
                    logString.append("gradedBy=");
                    logString.append(AgentFacade.getAgentString());
                    logString.append(", itemGradingId=");
                    logString.append(data.getItemGradingId());

                    if (updateScore) {
                        data.setAutoScore(Double.valueOf(newAutoScore));
                        logString.append(", newAutoScore=");
                        logString.append(newAutoScore);
                        logString.append(", oldAutoScore=");
                        logString.append(oldAutoScore);
                    }
                    if (updateComments) {
                        data.setComments(newComments);
                        logString.append(", newComments=");
                        logString.append(newComments);
                        logString.append(", oldComments=");
                        logString.append(oldComments);
                    }
                    if (updateScore || updateComments) {
                        updateFlag = true;
                        data.setGradedBy(AgentFacade.getAgentString());
                        data.setGradedDate(new Date());
                        String targetString = "siteId=" + AgentFacade.getCurrentSiteId() + ", "
                                + logString.toString();
                        String safeString = targetString.length() > 255 ? targetString.substring(0, 255)
                                : targetString;
                        EventTrackingService.post(
                                EventTrackingService.newEvent("sam.student.score.update", safeString, true));
                        log.debug("****4 itemGradingId=" + data.getItemGradingId());
                        log.debug("****5 set points = " + data.getAutoScore() + ", comments to "
                                + data.getComments());
                    }
                    data.setAnswerText(ContextUtil.stringWYSIWYG(data.getAnswerText()));
                    itemGradingSet.add(data);
                }
            }
            if (adata == null) {
                // this is for cases when studnet submitted an assessment but skipped all teh questions
                // when we won't be able to get teh assessmentGrading based on itemGrdaing ('cos there is none).
                String assessmentGradingId = cu.lookupParam("gradingData");
                adata = delegate.load(assessmentGradingId);
            }
            adata.setItemGradingSet(itemGradingSet);
        }

        if (adata == null)
            return true; // Nothing to save.

        String newComments = TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, bean.getComments());
        if (newComments != null) {
            newComments = newComments.trim();
        } else {
            newComments = "";
        }
        String oldComments = adata.getComments();
        if (oldComments != null) {
            oldComments = oldComments.trim();
        } else {
            oldComments = "";
        }

        if (!newComments.equals(oldComments)) {
            updateFlag = true;
            adata.setComments(newComments);
            adata.setGradedBy(AgentFacade.getAgentString());
            adata.setGradedDate(new Date());
            StringBuffer logString = new StringBuffer();
            logString.append("gradedBy=");
            logString.append(AgentFacade.getAgentString());
            logString.append(", assessmentGradingId=");
            logString.append(adata.getAssessmentGradingId());
            logString.append(", newComments=");
            logString.append(newComments);
            logString.append(", oldComments=");
            logString.append(oldComments);
            EventTrackingService.post(
                    EventTrackingService.newEvent("sam.student.score.update", logString.toString(), true));
        }

        if (updateFlag) {
            delegate.updateAssessmentGradingScore(adata, tbean.getPublishedAssessment());
        }
        log.debug("Saved student scores.");

        updateAttachment(delivery);

    } catch (GradebookServiceException ge) {
        FacesContext context = FacesContext.getCurrentInstance();
        String err = (String) cu.getLocalizedString("org.sakaiproject.tool.assessment.bundle.AuthorMessages",
                "gradebook_exception_error");
        context.addMessage(null, new FacesMessage(err));

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:org.sakaiproject.tool.assessment.ui.listener.evaluation.TotalScoreUpdateListener.java

private boolean needUpdate(AgentResults agentResults, HashMap map, StringBuilder newScoreString)
        throws NumberFormatException {
    boolean update = true;
    String newComments = TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log,
            agentResults.getComments());
    agentResults.setComments(newComments);
    log.debug("newComments = " + newComments);

    double totalAutoScore = 0;
    if (agentResults.getTotalAutoScore() != null && !("").equals(agentResults.getTotalAutoScore())) {
        try {/*from w  w w  .j a v a  2 s.  c om*/
            totalAutoScore = Double.valueOf(agentResults.getTotalAutoScore()).doubleValue();
        } catch (NumberFormatException e) {
            totalAutoScore = 0;
        }
    }

    double totalOverrideScore = 0;
    Boolean newIsLate = agentResults.getIsLate(); // if the duedate were postpond, we need to adjust this
    // we will check if there is change of grade. if so, add up new score
    // else skip
    AssessmentGradingData old = (AssessmentGradingData) map.get(agentResults.getAssessmentGradingId());
    if (old != null) {
        if (agentResults.getTotalOverrideScore() != null
                && !("").equals(agentResults.getTotalOverrideScore())) {
            try {
                totalOverrideScore = Double.valueOf(agentResults.getTotalOverrideScore()).doubleValue();
            } catch (NumberFormatException e) {
                log.warn("Adj has wrong input type" + e);
                throw e;
            }
        }

        double newScore = totalAutoScore + totalOverrideScore;
        newScoreString.append(Double.valueOf(newScore));
        double oldScore = 0;
        if (old.getFinalScore() != null) {
            oldScore = old.getFinalScore().doubleValue();
        }
        Boolean oldIsLate = old.getIsLate();

        String oldComments = old.getComments();
        log.debug("***oldScore = " + oldScore);
        log.debug("***newScore = " + newScore);
        log.debug("***oldIsLate = " + oldIsLate);
        log.debug("***newIsLate = " + newIsLate);
        log.debug("***oldComments = " + oldComments);
        log.debug("***newComments = " + newComments);
        if (MathUtils.equalsIncludingNaN(oldScore, newScore, 0.0001) && newIsLate.equals(oldIsLate)
                && ((newComments != null && newComments.equals(oldComments))
                        || (newComments == null && oldComments == null)
                        // following condition will happen when there is no comments (null) and user clicks on SubmissionId.
                        // getComments() in AgentResults calls Validator.check(comments, "") so the null comment gets set to ""
                        // there is nothing updated. update flag should be false
                        || ((newComments != null && newComments.equals("")) && oldComments == null))) {
            update = false;
        }
    } else { // no assessmentGradingData exists
        boolean noOverrideScore = false;
        boolean noComment = false;
        String score = agentResults.getTotalOverrideScore();
        if (score != null) {
            if (!("").equals(score.trim()) && !("-").equals(score.trim())) {
                try {
                    totalOverrideScore = Double.valueOf(agentResults.getTotalOverrideScore()).doubleValue();
                    noOverrideScore = false;
                } catch (NumberFormatException e) {
                    log.warn("Adj has wrong input type" + e);
                    throw e;
                }
            } else {
                noOverrideScore = true;
                totalAutoScore = 0;
            }
        } else {
            noOverrideScore = true;
            totalAutoScore = 0;
        }
        double newScore = totalAutoScore + totalOverrideScore;
        newScoreString.append(Double.valueOf(newScore));

        if ("".equals(agentResults.getComments().trim()))
            noComment = true;

        if (noOverrideScore && noComment)
            update = false;
    }
    return update;
}