Example usage for org.apache.commons.beanutils BeanUtils populate

List of usage examples for org.apache.commons.beanutils BeanUtils populate

Introduction

In this page you can find the example usage for org.apache.commons.beanutils BeanUtils populate.

Prototype

public static void populate(Object bean, Map properties) 

Source Link

Usage

From source file:org.red5.io.utils.ConversionUtils.java

/**
 * Convert map to bean/*  www .  j  a  va2  s. co m*/
 * 
 * @param source
 *            Source map
 * @param target
 *            Target class
 * @return Bean of that class
 * @throws ConversionException
 *             on failure
 */
public static Object convertMapToBean(Map<String, ? extends Object> source, Class<?> target)
        throws ConversionException {
    Object bean = newInstance(target);
    if (bean == null) {
        //try with just the target name as specified in Trac #352
        bean = newInstance(target.getName());
        if (bean == null) {
            throw new ConversionException("Unable to create bean using empty constructor");
        }
    }
    try {
        BeanUtils.populate(bean, source);
    } catch (Exception e) {
        throw new ConversionException("Error populating bean", e);
    }
    return bean;
}

From source file:org.red5.server.service.ConversionUtils.java

/**
 * Convert map to bean/*from   ww w. j a va2s .co m*/
 * @param source                Source map
 * @param target                Target class
 * @return                      Bean of that class
 * @throws ConversionException
 */
public static Object convertMapToBean(Map<?, ?> source, Class<?> target) throws ConversionException {
    Object bean = newInstance(target.getClass().getName());
    if (bean == null) {
        throw new ConversionException("Unable to create bean using empty constructor");
    }
    try {
        BeanUtils.populate(bean, source);
    } catch (Exception e) {
        throw new ConversionException("Error populating bean", e);
    }
    return bean;
}

From source file:org.red5.server.util.ConversionUtils.java

/**
 * Convert map to bean/*ww w .  j  a v  a  2  s  .  c  o m*/
 * @param source                Source map
 * @param target                Target class
 * @return                      Bean of that class
 * @throws ConversionException on failure
 */
public static Object convertMapToBean(Map<?, ?> source, Class<?> target) throws ConversionException {
    Object bean = newInstance(target);
    if (bean == null) {
        //try with just the target name as specified in Trac #352
        bean = newInstance(target.getName());
        if (bean == null) {
            throw new ConversionException("Unable to create bean using empty constructor");
        }
    }
    try {
        BeanUtils.populate(bean, source);
    } catch (Exception e) {
        throw new ConversionException("Error populating bean", e);
    }
    return bean;
}

From source file:org.sakaiproject.tool.assessment.qti.util.XmlMapper.java

/**
 * Maps each element node to a bean property.
 * Supports only simple types such as String, int and long, plus Lists.
 *
 * If node is a document it processes it as if it were the root node.
 *
 * If there are multiple nodes with the same element name they will be stored
 * in a List.//from  w  w w.  j av  a 2s .c o  m
 *
 * NOTE:
 * This is DESIGNED to ignore elements at more depth so that simple
 * String key value pairs are used.  This WILL NOT recurse to more depth,
 * by design.  If it did so, you would have to use maps of maps.
 *
 * @param bean Serializable object which has the appropriate setters/getters
 * @param doc the document
 */
static public void populateBeanFromDoc(Serializable bean, Document doc) {
    try {
        Map m = map(doc);
        BeanUtils.populate(bean, m);
    } catch (Exception e) {
        log.error(e);
        throw new RuntimeException(e);
    }
}

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

/**
 * Calculate the detailed statistics//w  ww .j a  v a2 s.c o  m
 * 
 * This will populate the HistogramScoresBean with the data associated with the
 * particular versioned assessment based on the publishedId.
 *
 * Some of this code will change when we move this to Hibernate persistence.
 * @param publishedId String
 * @param histogramScores TotalScoresBean
 * @return boolean true if successful
 */
public boolean histogramScores(HistogramScoresBean histogramScores, TotalScoresBean totalScores) {
    DeliveryBean delivery = (DeliveryBean) ContextUtil.lookupBean("delivery");
    String publishedId = totalScores.getPublishedId();
    if (publishedId.equals("0")) {
        publishedId = (String) ContextUtil.lookupParam("publishedAssessmentId");
    }
    String actionString = ContextUtil.lookupParam("actionString");
    // See if this can fix SAK-16437
    if (actionString != null && !actionString.equals("reviewAssessment")) {
        // Shouldn't come to here. The action should either be null or reviewAssessment.
        // If we can confirm this is where causes SAK-16437, ask UX for a new screen with warning message.  
        log.error("SAK-16437 happens!! publishedId = " + publishedId + ", agentId = "
                + AgentFacade.getAgentString());
    }

    ResourceLoader rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages");
    ResourceLoader rbEval = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages");
    String assessmentName = "";

    histogramScores.clearLowerQuartileStudents();
    histogramScores.clearUpperQuartileStudents();

    String which = histogramScores.getAllSubmissions();
    if (which == null && totalScores.getAllSubmissions() != null) {
        // use totalscore's selection
        which = totalScores.getAllSubmissions();
        histogramScores.setAllSubmissions(which); // changed submission pulldown
    }

    histogramScores.setItemId(ContextUtil.lookupParam("itemId"));
    histogramScores.setHasNav(ContextUtil.lookupParam("hasNav"));

    GradingService delegate = new GradingService();
    PublishedAssessmentService pubService = new PublishedAssessmentService();
    List<AssessmentGradingData> allscores = delegate.getTotalScores(publishedId, which);
    //set the ItemGradingData manually here. or we cannot
    //retrieve it later.
    for (AssessmentGradingData agd : allscores) {
        agd.setItemGradingSet(delegate.getItemGradingSet(String.valueOf(agd.getAssessmentGradingId())));
    }
    if (allscores.isEmpty()) {
        // Similar case in Bug 1537, but clicking Statistics link instead of assignment title.
        // Therefore, redirect the the same page.
        delivery.setOutcome("reviewAssessmentError");
        delivery.setActionString(actionString);
        return true;
    }

    histogramScores.setPublishedId(publishedId);
    int callerName = TotalScoresBean.CALLED_FROM_HISTOGRAM_LISTENER;
    String isFromStudent = (String) ContextUtil.lookupParam("isFromStudent");
    if (isFromStudent != null && "true".equals(isFromStudent)) {
        callerName = TotalScoresBean.CALLED_FROM_HISTOGRAM_LISTENER_STUDENT;
    }

    // get the Map of all users(keyed on userid) belong to the selected sections 
    // now we only include scores of users belong to the selected sections
    Map useridMap = null;
    ArrayList scores = new ArrayList();
    // only do section filter if it's published to authenticated users
    if (totalScores.getReleaseToAnonymous()) {
        scores.addAll(allscores);
    } else {
        useridMap = totalScores.getUserIdMap(callerName);
        Iterator allscores_iter = allscores.iterator();
        while (allscores_iter.hasNext()) {
            AssessmentGradingData data = (AssessmentGradingData) allscores_iter.next();
            String agentid = data.getAgentId();
            if (useridMap.containsKey(agentid)) {
                scores.add(data);
            }
        }
    }
    Iterator iter = scores.iterator();
    //log.info("Has this many agents: " + scores.size());

    if (!iter.hasNext()) {
        log.info("Students who have submitted may have been removed from this site");
        return false;
    }

    // here scores contain AssessmentGradingData 
    Map assessmentMap = getAssessmentStatisticsMap(scores);

    /*
     * find students in upper and lower quartiles 
     * of assessment scores
     */
    ArrayList submissionsSortedForDiscrim = new ArrayList(scores);
    boolean anonymous = Boolean.valueOf(totalScores.getAnonymous()).booleanValue();
    Collections.sort(submissionsSortedForDiscrim,
            new AssessmentGradingComparatorByScoreAndUniqueIdentifier(anonymous));
    int numSubmissions = scores.size();
    //int percent27 = ((numSubmissions*10*27/100)+5)/10; // rounded
    int percent27 = numSubmissions * 27 / 100; // rounded down
    if (percent27 == 0)
        percent27 = 1;
    for (int i = 0; i < percent27; i++) {
        histogramScores.addToLowerQuartileStudents(
                ((AssessmentGradingData) submissionsSortedForDiscrim.get(i)).getAgentId());
        histogramScores.addToUpperQuartileStudents(
                ((AssessmentGradingData) submissionsSortedForDiscrim.get(numSubmissions - 1 - i)).getAgentId());
    }

    PublishedAssessmentIfc pub = (PublishedAssessmentIfc) pubService.getPublishedAssessment(publishedId, false);

    if (pub != null) {
        if (actionString != null && actionString.equals("reviewAssessment")) {
            if (AssessmentIfc.RETRACT_FOR_EDIT_STATUS.equals(pub.getStatus())) {
                // Bug 1547: If this is during review and the assessment is retracted for edit now, 
                // set the outcome to isRetractedForEdit2 error page.
                delivery.setOutcome("isRetractedForEdit2");
                delivery.setActionString(actionString);
                return true;
            } else {
                delivery.setOutcome("histogramScores");
                delivery.setSecureDeliveryHTMLFragment("");
                delivery.setBlockDelivery(false);
                SecureDeliveryServiceAPI secureDelivery = SamigoApiFactory.getInstance()
                        .getSecureDeliveryServiceAPI();
                if (secureDelivery.isSecureDeliveryAvaliable()) {

                    String moduleId = pub.getAssessmentMetaDataByLabel(SecureDeliveryServiceAPI.MODULE_KEY);
                    if (moduleId != null && !SecureDeliveryServiceAPI.NONE_ID.equals(moduleId)) {

                        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance()
                                .getExternalContext().getRequest();
                        PhaseStatus status = secureDelivery.validatePhase(moduleId, Phase.ASSESSMENT_REVIEW,
                                pub, request);
                        delivery.setSecureDeliveryHTMLFragment(secureDelivery.getHTMLFragment(moduleId, pub,
                                request, Phase.ASSESSMENT_REVIEW, status, new ResourceLoader().getLocale()));
                        if (PhaseStatus.FAILURE == status) {
                            delivery.setOutcome("secureDeliveryError");
                            delivery.setActionString(actionString);
                            delivery.setBlockDelivery(true);
                            return true;
                        }
                    }
                }
            }
        }

        boolean showObjectivesColumn = Boolean
                .parseBoolean(pub.getAssessmentMetaDataByLabel(AssessmentBaseIfc.HASMETADATAFORQUESTIONS));
        Map<String, Double> objectivesCorrect = new HashMap<String, Double>();
        Map<String, Integer> objectivesCounter = new HashMap<String, Integer>();
        Map<String, Double> keywordsCorrect = new HashMap<String, Double>();
        Map<String, Integer> keywordsCounter = new HashMap<String, Integer>();

        assessmentName = pub.getTitle();

        List<? extends SectionDataIfc> parts = pub.getSectionArraySorted();
        histogramScores.setAssesmentParts((List<PublishedSectionData>) parts);
        ArrayList info = new ArrayList();
        Iterator partsIter = parts.iterator();
        int secseq = 1;
        double totalpossible = 0;
        boolean hasRandompart = false;
        boolean isRandompart = false;
        String poolName = null;

        HashMap itemScoresMap = delegate.getItemScores(Long.valueOf(publishedId), Long.valueOf(0), which);
        HashMap itemScores = new HashMap();

        if (totalScores.getReleaseToAnonymous()) {
            // skip section filter if it's published to anonymous users
            itemScores.putAll(itemScoresMap);
        } else {
            if (useridMap == null) {
                useridMap = totalScores.getUserIdMap(callerName);
            }

            for (Iterator it = itemScoresMap.entrySet().iterator(); it.hasNext();) {
                Map.Entry entry = (Map.Entry) it.next();
                Long itemId = (Long) entry.getKey();
                ArrayList itemScoresList = (ArrayList) entry.getValue();

                ArrayList filteredItemScoresList = new ArrayList();
                Iterator itemScoresIter = itemScoresList.iterator();
                // get the Map of all users(keyed on userid) belong to the
                // selected sections

                while (itemScoresIter.hasNext()) {
                    ItemGradingData idata = (ItemGradingData) itemScoresIter.next();
                    String agentid = idata.getAgentId();
                    if (useridMap.containsKey(agentid)) {
                        filteredItemScoresList.add(idata);
                    }
                }
                itemScores.put(itemId, filteredItemScoresList);
            }
        }

        // Iterate through the assessment parts
        while (partsIter.hasNext()) {
            SectionDataIfc section = (SectionDataIfc) partsIter.next();
            String authortype = section.getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE);
            try {
                if (SectionDataIfc.RANDOM_DRAW_FROM_QUESTIONPOOL.equals(Integer.valueOf(authortype))) {
                    hasRandompart = true;
                    isRandompart = true;
                    poolName = section.getSectionMetaDataByLabel(SectionDataIfc.POOLNAME_FOR_RANDOM_DRAW);
                } else {
                    isRandompart = false;
                    poolName = null;
                }
            } catch (NumberFormatException e) {
                isRandompart = false;
                poolName = null;
            }
            if (section.getSequence() == null)
                section.setSequence(Integer.valueOf(secseq++));
            String title = rb.getString("part") + " " + section.getSequence().toString();
            title += ", " + rb.getString("question") + " ";
            List<ItemDataIfc> itemset = section.getItemArraySortedForGrading();
            int seq = 1;
            Iterator<ItemDataIfc> itemsIter = itemset.iterator();

            // Iterate through the assessment questions (items)
            while (itemsIter.hasNext()) {
                HistogramQuestionScoresBean questionScores = new HistogramQuestionScoresBean();
                questionScores.setNumberOfParts(parts.size());
                //if this part is a randompart , then set randompart = true
                questionScores.setRandomType(isRandompart);
                questionScores.setPoolName(poolName);
                ItemDataIfc item = itemsIter.next();

                if (showObjectivesColumn) {
                    String obj = item.getItemMetaDataByLabel(ItemMetaDataIfc.OBJECTIVE);
                    questionScores.setObjectives(obj);
                    String key = item.getItemMetaDataByLabel(ItemMetaDataIfc.KEYWORD);
                    questionScores.setKeywords(key);
                }

                //String type = delegate.getTextForId(item.getTypeId());
                String type = getType(item.getTypeId().intValue());
                if (item.getSequence() == null)
                    item.setSequence(Integer.valueOf(seq++));

                questionScores.setPartNumber(section.getSequence().toString());
                //set the question label depending on random pools and parts
                if (questionScores.getRandomType() && poolName != null) {
                    if (questionScores.getNumberOfParts() > 1) {
                        questionScores.setQuestionLabelFormat(rb.getString("label_question_part_pool", null));
                    } else {
                        questionScores.setQuestionLabelFormat(rb.getString("label_question_pool", null));
                    }
                } else {
                    if (questionScores.getNumberOfParts() > 1) {
                        questionScores.setQuestionLabelFormat(rb.getString("label_question_part", null));
                    } else {
                        questionScores.setQuestionLabelFormat(rb.getString("label_question", null));
                    }
                }
                questionScores.setQuestionNumber(item.getSequence().toString());
                questionScores.setItemId(item.getItemId());
                questionScores.setTitle(title + item.getSequence().toString() + " (" + type + ")");

                if (item.getTypeId().equals(TypeIfc.EXTENDED_MATCHING_ITEMS)) { // emi question
                    questionScores.setQuestionText(item.getLeadInText());
                } else {
                    questionScores.setQuestionText(item.getText());
                }

                questionScores.setQuestionType(item.getTypeId().toString());
                //totalpossible = totalpossible + item.getScore().doubleValue();
                //ArrayList responses = null;

                //for each question (item) in the published assessment's current part/section
                determineResults(pub, questionScores, (ArrayList) itemScores.get(item.getItemId()));
                questionScores.setTotalScore(item.getScore().toString());

                questionScores.setN("" + numSubmissions);
                questionScores.setItemId(item.getItemId());
                Set studentsWithAllCorrect = questionScores.getStudentsWithAllCorrect();
                Set studentsResponded = questionScores.getStudentsResponded();
                if (studentsWithAllCorrect == null || studentsResponded == null
                        || studentsWithAllCorrect.isEmpty() || studentsResponded.isEmpty()) {
                    questionScores.setPercentCorrectFromUpperQuartileStudents("0");
                    questionScores.setPercentCorrectFromLowerQuartileStudents("0");
                    questionScores.setDiscrimination("0.0");
                } else {
                    int percent27ForThisQuestion = percent27;
                    Set<String> upperQuartileStudents = histogramScores.getUpperQuartileStudents().keySet();
                    Set<String> lowerQuartileStudents = histogramScores.getLowerQuartileStudents().keySet();
                    if (isRandompart) {
                        //we need to calculate the 27% upper and lower
                        //per question for the people that actually answered
                        //this question.
                        upperQuartileStudents = new HashSet<String>();
                        lowerQuartileStudents = new HashSet<String>();
                        percent27ForThisQuestion = questionScores.getNumResponses() * 27 / 100;
                        if (percent27ForThisQuestion == 0)
                            percent27ForThisQuestion = 1;
                        if (questionScores.getNumResponses() != 0) {
                            //need to only get gradings for students that answered this question
                            List<AssessmentGradingData> filteredGradings = filterGradingData(
                                    submissionsSortedForDiscrim, questionScores.getItemId());

                            // SAM-2228: loop control issues because of unsynchronized collection access
                            int filteredGradingsSize = filteredGradings.size();
                            percent27ForThisQuestion = filteredGradingsSize * 27 / 100;

                            for (int i = 0; i < percent27ForThisQuestion; i++) {
                                lowerQuartileStudents
                                        .add(((AssessmentGradingData) filteredGradings.get(i)).getAgentId());
                                //
                                upperQuartileStudents.add(((AssessmentGradingData) filteredGradings
                                        .get(filteredGradingsSize - 1 - i)).getAgentId());
                            }
                        }
                    }
                    if (questionScores.getNumResponses() != 0) {
                        int numStudentsWithAllCorrectFromUpperQuartile = 0;
                        int numStudentsWithAllCorrectFromLowerQuartile = 0;
                        Iterator studentsIter = studentsWithAllCorrect.iterator();
                        while (studentsIter.hasNext()) {
                            String agentId = (String) studentsIter.next();
                            if (upperQuartileStudents.contains(agentId)) {
                                numStudentsWithAllCorrectFromUpperQuartile++;
                            }
                            if (lowerQuartileStudents.contains(agentId)) {
                                numStudentsWithAllCorrectFromLowerQuartile++;
                            }
                        }

                        double percentCorrectFromUpperQuartileStudents = ((double) numStudentsWithAllCorrectFromUpperQuartile
                                / (double) percent27ForThisQuestion) * 100d;

                        double percentCorrectFromLowerQuartileStudents = ((double) numStudentsWithAllCorrectFromLowerQuartile
                                / (double) percent27ForThisQuestion) * 100d;

                        questionScores.setPercentCorrectFromUpperQuartileStudents(
                                Integer.toString((int) percentCorrectFromUpperQuartileStudents));
                        questionScores.setPercentCorrectFromLowerQuartileStudents(
                                Integer.toString((int) percentCorrectFromLowerQuartileStudents));

                        double discrimination = ((double) numStudentsWithAllCorrectFromUpperQuartile
                                - (double) numStudentsWithAllCorrectFromLowerQuartile)
                                / (double) percent27ForThisQuestion;

                        // round to 2 decimals
                        if (discrimination > 999999 || discrimination < -999999) {
                            questionScores.setDiscrimination("NaN");
                        } else {
                            discrimination = ((int) (discrimination * 100.00d)) / 100.00d;
                            questionScores.setDiscrimination(Double.toString(discrimination));
                        }
                    } else {
                        questionScores.setPercentCorrectFromUpperQuartileStudents(rbEval.getString("na"));
                        questionScores.setPercentCorrectFromLowerQuartileStudents(rbEval.getString("na"));
                        questionScores.setDiscrimination(rbEval.getString("na"));
                    }
                }

                info.add(questionScores);
            } // end-while - items

            totalpossible = pub.getTotalScore().doubleValue();

        } // end-while - parts
        histogramScores.setInfo(info);
        histogramScores.setRandomType(hasRandompart);

        int maxNumOfAnswers = 0;
        List<HistogramQuestionScoresBean> detailedStatistics = new ArrayList<HistogramQuestionScoresBean>();
        Iterator infoIter = info.iterator();
        while (infoIter.hasNext()) {
            HistogramQuestionScoresBean questionScores = (HistogramQuestionScoresBean) infoIter.next();
            if (questionScores.getQuestionType().equals(TypeIfc.MULTIPLE_CHOICE.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.MULTIPLE_CORRECT.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.TRUE_FALSE.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.FILL_IN_BLANK.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.MATCHING.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.FILL_IN_NUMERIC.toString())
                    || questionScores.getQuestionType()
                            .equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.CALCULATED_QUESTION.toString())
                    || questionScores.getQuestionType().equals("16")) {
                questionScores.setShowIndividualAnswersInDetailedStatistics(true);
                detailedStatistics.add(questionScores);
                if (questionScores.getHistogramBars() != null) {
                    maxNumOfAnswers = questionScores.getHistogramBars().length > maxNumOfAnswers
                            ? questionScores.getHistogramBars().length
                            : maxNumOfAnswers;
                }
            }

            if (showObjectivesColumn) {
                // Get the percentage correct by objective
                String obj = questionScores.getObjectives();
                if (obj != null && !"".equals(obj)) {
                    String[] objs = obj.split(",");
                    for (int i = 0; i < objs.length; i++) {

                        // SAM-2508 set a default value to avoid the NumberFormatException issues
                        Double pctCorrect = 0.0d;
                        Double newAvg = 0.0d;
                        int divisor = 1;

                        try {
                            if (questionScores.getPercentCorrect() != null
                                    && !"N/A".equalsIgnoreCase(questionScores.getPercentCorrect())) {
                                pctCorrect = Double.parseDouble(questionScores.getPercentCorrect());
                            }
                        } catch (NumberFormatException nfe) {
                            log.error("NFE when looking at metadata and objectives", nfe);
                        }

                        if (objectivesCorrect.get(objs[i]) != null) {
                            Double objCorrect = objectivesCorrect.get(objs[i]);
                            divisor = objCorrect.intValue() + 1;

                            newAvg = objCorrect + ((pctCorrect - objCorrect) / divisor);
                            newAvg = new BigDecimal(newAvg).setScale(2, RoundingMode.HALF_UP).doubleValue();
                        } else {
                            newAvg = new BigDecimal(pctCorrect).setScale(2, RoundingMode.HALF_UP).doubleValue();
                        }

                        objectivesCounter.put(objs[i], divisor);
                        objectivesCorrect.put(objs[i], newAvg);
                    }
                }

                // Get the percentage correct by keyword
                String key = questionScores.getKeywords();
                if (key != null && !"".equals(key)) {
                    String[] keys = key.split(",");
                    for (int i = 0; i < keys.length; i++) {
                        if (keywordsCorrect.get(keys[i]) != null) {
                            int divisor = keywordsCounter.get(keys[i]) + 1;
                            Double newAvg = keywordsCorrect.get(keys[i])
                                    + ((Double.parseDouble(questionScores.getPercentCorrect())
                                            - keywordsCorrect.get(keys[i])) / divisor);

                            newAvg = new BigDecimal(newAvg).setScale(2, RoundingMode.HALF_UP).doubleValue();

                            keywordsCounter.put(keys[i], divisor);
                            keywordsCorrect.put(keys[i], newAvg);
                        } else {
                            Double newAvg = Double.parseDouble(questionScores.getPercentCorrect());
                            newAvg = new BigDecimal(newAvg).setScale(2, RoundingMode.HALF_UP).doubleValue();

                            keywordsCounter.put(keys[i], 1);
                            keywordsCorrect.put(keys[i], newAvg);
                        }
                    }
                }
            }

            //i.e. for EMI questions we add detailed stats for the whole
            //question as well as for the sub-questions
            if (questionScores.getQuestionType().equals(TypeIfc.EXTENDED_MATCHING_ITEMS.toString())) {
                questionScores.setShowIndividualAnswersInDetailedStatistics(false);
                detailedStatistics.addAll(questionScores.getInfo());

                Iterator subInfoIter = questionScores.getInfo().iterator();
                while (subInfoIter.hasNext()) {
                    HistogramQuestionScoresBean subQuestionScores = (HistogramQuestionScoresBean) subInfoIter
                            .next();
                    if (subQuestionScores.getHistogramBars() != null) {
                        subQuestionScores.setN(questionScores.getN());
                        maxNumOfAnswers = subQuestionScores.getHistogramBars().length > maxNumOfAnswers
                                ? subQuestionScores.getHistogramBars().length
                                : maxNumOfAnswers;
                    }
                }
                /*                 
                                 Object numberOfStudentsWithZeroAnswers = numberOfStudentsWithZeroAnswersForQuestion.get(questionScores.getItemId());
                                 if (numberOfStudentsWithZeroAnswers == null) {
                                    questionScores.setNumberOfStudentsWithZeroAnswers(0);
                                 }
                                 else {
                                    questionScores.setNumberOfStudentsWithZeroAnswers( ((Integer) numberOfStudentsWithZeroAnswersForQuestion.get(questionScores.getItemId())).intValue() );
                                 }
                */
            }

        }
        //VULA-1948: sort the detailedStatistics list by Question Label
        sortQuestionScoresByLabel(detailedStatistics);
        histogramScores.setDetailedStatistics(detailedStatistics);
        histogramScores.setMaxNumberOfAnswers(maxNumOfAnswers);
        histogramScores.setShowObjectivesColumn(showObjectivesColumn);

        if (showObjectivesColumn) {
            List<Entry<String, Double>> objectivesList = new ArrayList<Entry<String, Double>>(
                    objectivesCorrect.entrySet());
            Collections.sort(objectivesList, new Comparator<Entry<String, Double>>() {
                public int compare(Entry<String, Double> e1, Entry<String, Double> e2) {
                    return e1.getKey().compareTo(e2.getKey());
                }
            });
            histogramScores.setObjectives(objectivesList);

            List<Entry<String, Double>> keywordsList = new ArrayList<Entry<String, Double>>(
                    keywordsCorrect.entrySet());

            Collections.sort(keywordsList, new Comparator<Entry<String, Double>>() {
                public int compare(Entry<String, Double> e1, Entry<String, Double> e2) {
                    return e1.getKey().compareTo(e2.getKey());
                }
            });
            histogramScores.setKeywords(keywordsList);
        }

        // test to see if it gets back empty map
        if (assessmentMap.isEmpty()) {
            histogramScores.setNumResponses(0);
        }

        try {
            BeanUtils.populate(histogramScores, assessmentMap);

            // quartiles don't seem to be working, workaround
            histogramScores.setQ1((String) assessmentMap.get("q1"));
            histogramScores.setQ2((String) assessmentMap.get("q2"));
            histogramScores.setQ3((String) assessmentMap.get("q3"));
            histogramScores.setQ4((String) assessmentMap.get("q4"));
            histogramScores.setTotalScore((String) assessmentMap.get("totalScore"));
            histogramScores.setTotalPossibleScore(Double.toString(totalpossible));
            HistogramBarBean[] bars = new HistogramBarBean[histogramScores.getColumnHeight().length];
            for (int i = 0; i < histogramScores.getColumnHeight().length; i++) {
                bars[i] = new HistogramBarBean();
                bars[i].setColumnHeight(Integer.toString(histogramScores.getColumnHeight()[i]));
                bars[i].setNumStudents(histogramScores.getNumStudentCollection()[i]);
                bars[i].setRangeInfo(histogramScores.getRangeCollection()[i]);
                //log.info("Set bar " + i + ": " + bean.getColumnHeight()[i] + ", " + bean.getNumStudentCollection()[i] + ", " + bean.getRangeCollection()[i]);
            }
            histogramScores.setHistogramBars(bars);

            ///////////////////////////////////////////////////////////
            // START DEBUGGING
            /*
              log.info("TESTING ASSESSMENT MAP");
              log.info("assessmentMap: =>");
              log.info(assessmentMap);
              log.info("--------------------------------------------");
              log.info("TESTING TOTALS HISTOGRAM FORM");
              log.info(
              "HistogramScoresForm Form: =>\n" + "bean.getMean()=" +
              bean.getMean() + "\n" +
              "bean.getColumnHeight()[0] (first elem)=" +
              bean.getColumnHeight()[0] + "\n" + "bean.getInterval()=" +
              bean.getInterval() + "\n" + "bean.getLowerQuartile()=" +
              bean.getLowerQuartile() + "\n" + "bean.getMaxScore()=" +
              bean.getMaxScore() + "\n" + "bean.getMean()=" + bean.getMean() +
              "\n" + "bean.getMedian()=" + bean.getMedian() + "\n" +
              "bean.getNumResponses()=" + bean.getNumResponses() + "\n" +
              "bean.getNumStudentCollection()=" +
              bean.getNumStudentCollection() +
              "\n" + "bean.getQ1()=" + bean.getQ1() + "\n" + "bean.getQ2()=" +
              bean.getQ2() + "\n" + "bean.getQ3()=" + bean.getQ3() + "\n" +
              "bean.getQ4()=" + bean.getQ4());
              log.info("--------------------------------------------");
                    
             */
            // END DEBUGGING CODE
            ///////////////////////////////////////////////////////////
        } catch (IllegalAccessException e) {
            log.warn("IllegalAccessException:  unable to populate bean" + e);
        } catch (InvocationTargetException e) {
            log.warn("InvocationTargetException: unable to populate bean" + e);
        }

        histogramScores.setAssessmentName(assessmentName);
    } else {
        log.error("pub is null. publishedId = " + publishedId);
        return false;
    }
    return true;
}

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

private void doScoreStatistics(HistogramQuestionScoresBean qbean, ArrayList scores) {
    // here scores contain ItemGradingData
    Map assessmentMap = getAssessmentStatisticsMap(scores);

    // test to see if it gets back empty map
    if (assessmentMap.isEmpty()) {
        qbean.setNumResponses(0);/*from  w ww. ja va 2  s.c om*/
    }

    try {
        BeanUtils.populate(qbean, assessmentMap);

        // quartiles don't seem to be working, workaround
        qbean.setQ1((String) assessmentMap.get("q1"));
        qbean.setQ2((String) assessmentMap.get("q2"));
        qbean.setQ3((String) assessmentMap.get("q3"));
        qbean.setQ4((String) assessmentMap.get("q4"));
        //qbean.setTotalScore( (String) assessmentMap.get("maxScore"));

        HistogramBarBean[] bars = new HistogramBarBean[qbean.getColumnHeight().length];

        // SAK-1933: if there is no response, do not show bars at all 
        // do not check if assessmentMap is empty, because it's never empty.
        if (scores.size() == 0) {
            bars = new HistogramBarBean[0];
        } else {
            for (int i = 0; i < qbean.getColumnHeight().length; i++) {
                bars[i] = new HistogramBarBean();
                bars[i].setColumnHeight(Integer.toString(qbean.getColumnHeight()[i]));
                bars[i].setNumStudents(qbean.getNumStudentCollection()[i]);
                if (qbean.getNumStudentCollection()[i] > 1) {
                    bars[i].setNumStudentsText(qbean.getNumStudentCollection()[i] + " Responses");
                } else {
                    bars[i].setNumStudentsText(qbean.getNumStudentCollection()[i] + " Response");

                }
                //  bars[i].setNumStudentsText(qbean.getNumStudentCollection()[i] +
                // " Responses");
                bars[i].setRangeInfo(qbean.getRangeCollection()[i]);
                bars[i].setLabel(qbean.getRangeCollection()[i]);
            }
        }
        qbean.setHistogramBars(bars);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}

From source file:org.seasar.struts.pojo.processor.commands.PopulateCheckboxProperty.java

private void populate(ActionContext actionContext, ActionForm actionForm) throws ServletException {
    Map parameters = getCheckBoxParameters(actionContext.getActionConfig(), actionContext.getParameterMap());
    if (!parameters.isEmpty()) {
        try {//from w  w w  . ja v a  2s .  c  om
            BeanUtils.populate(actionForm, parameters);
        } catch (IllegalAccessException e) {
            throw new ServletException("BeanUtils.populate", e);
        } catch (InvocationTargetException e) {
            throw new ServletException("BeanUtils.populate", e);
        }
    }
}

From source file:org.seasar.struts.pojo.processor.ProcessCheckboxPopulateInterceptor.java

public Object invoke(MethodInvocation invocation) throws Throwable {
    HttpServletRequest request = (HttpServletRequest) invocation.getArguments()[0];

    if (request instanceof MultipartRequestWrapper) {
        invocation.proceed();// w w  w  .j a  va  2 s  . c  o m
        Map parameters = getCheckBoxParameters(request);
        if (!parameters.isEmpty()) {
            ActionForm form = (ActionForm) invocation.getArguments()[2];
            try {
                BeanUtils.populate(form, parameters);
            } catch (IllegalAccessException e) {
                throw new ServletException("BeanUtils.populate", e);
            } catch (InvocationTargetException e) {
                throw new ServletException("BeanUtils.populate", e);
            }
        }
    } else {
        Map parameters = getCheckBoxParameters(request);
        if (!parameters.isEmpty()) {
            S2ServletRequestWrapper s2request = new S2ServletRequestWrapper(request);
            addParameter(s2request, parameters);
            invocation.getArguments()[0] = s2request;
        }
        invocation.proceed();
    }

    return null;
}

From source file:org.shenjitang.mongodbutils.MongoDbOperater.java

public <T> T findOneObj(String dbName, String sql, Class<T> clazz)
        throws JSQLParserException, InstantiationException, IllegalAccessException, InvocationTargetException {
    Map map = findOne(dbName, sql);
    if (map == null) {
        return null;
    }//  w  ww.j a v a 2 s  .c om
    T obj = clazz.newInstance();
    ConvertUtils.register(new DateConverter(null), Date.class);
    ConvertUtils.register(new IntegerConverter(null), Integer.class);
    BeanUtils.populate(obj, map);
    return obj;
}

From source file:org.shenjitang.mongodbutils.MongoDbOperater.java

public <T> T findOneObj(String dbName, String collName, Map queryMap, Class<T> clazz)
        throws InstantiationException, IllegalAccessException, InvocationTargetException {
    DB db = mongoClient.getDB(dbName);/*from ww w.jav a2s .c o m*/
    DBCollection coll = db.getCollection(collName);
    BasicDBObject query = new BasicDBObject(queryMap);
    DBObject map = coll.findOne(query);
    if (map == null) {
        return null;
    }
    T obj = clazz.newInstance();
    ConvertUtils.register(new DateConverter(null), Date.class);
    ConvertUtils.register(new IntegerConverter(null), Integer.class);
    BeanUtils.populate(obj, map.toMap());
    return obj;
}