📄 reportgeneratorbean.java
字号:
/* * SchoolEJB - CyberDemia's library of EJBs for educational related services. * Copyright (C) 2003 CyberDemia Research and Services * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * See the COPYING file located in the top-level-directory of * the archive of this library for complete text of license. */package com.cyberdemia.school.impl;import javax.ejb.*;import javax.naming.*;import java.util.*;import com.cyberdemia.school.*;import java.util.logging.*;import com.cyberdemia.value.*;/*** ReportGeneratorBean is a session bean facade for retrieving and processing data * for reports based on historical records.** @author Alexander Yap*/public class ReportGeneratorBean implements SessionBean{ public ReportGeneratorBean() { try { Context ctx = new InitialContext(); m_testHome = (LocalTestHome)ctx.lookup("java:comp/env/ejb/localTest"); m_quesHome = (LocalQuestionHome)ctx.lookup("java:comp/env/ejb/localQuestion"); m_answerHistoryRecordHome = (LocalAnswerHistoryRecordHome)ctx.lookup("java:comp/env/ejb/localAnswerHistoryRecord"); } catch (NamingException nex) { throw SchoolUtils.convertToEJBException(nex); } } /** * Gets a user's historical records for a test and user. * @param testId Test ID * @param userId User ID * @return List of AnswerHistoryData instances. */ public List getAnswerHistory(String testId, String userId) { s_logger.fine("Getting answer history for test "+testId+", user "+userId); LinkedList historyList = new LinkedList(); try { Collection historyCol = m_answerHistoryRecordHome.findByUserAndTest(userId,testId); Iterator hIter=historyCol.iterator(); while (hIter.hasNext()) { LocalAnswerHistoryRecord record = (LocalAnswerHistoryRecord)hIter.next(); historyList.add( new AnswerHistoryData ( record.getTestId(), record.getQuestionId(), record.getUserId(), record.getQuestionIndex(), record.getQuestionScore(), record.getUserAnswer(), record.getCorrectAnswer(), record.isAnswerCorrect(), record.getTimestamp()) ); } } catch (FinderException fex) { s_logger.log( Level.SEVERE, "Error getting answer history for test "+testId+", user "+userId, fex); throw SchoolUtils.convertToEJBException(fex); } catch (RuntimeException ex) { s_logger.log( Level.SEVERE, "Error getting answer history for test "+testId+", user "+userId, ex); throw ex; } return historyList; } /** * Gets the distribution of users' answers for all the questions in a test. * @param testId Test ID * @return SortedMap containing the question indices (Integer objects) as the keys and count of correct answers (Integer objects) as the values. */ public SortedMap getAnswersDistributionForTest(String testId) { s_logger.fine("Getting answers distribution for test "+testId); Map tmpDistMap = new HashMap(); try { Collection historyCol = m_answerHistoryRecordHome.findByTest(testId); Iterator hIter=historyCol.iterator(); while (hIter.hasNext()) { LocalAnswerHistoryRecord record = (LocalAnswerHistoryRecord)hIter.next(); Integer quesIndex = new Integer(record.getQuestionIndex()); IntegerType correctAnswerCounter = (IntegerType)tmpDistMap.get(quesIndex); if (correctAnswerCounter==null) { correctAnswerCounter = new IntegerType(); tmpDistMap.put(quesIndex, correctAnswerCounter); } if (record.isAnswerCorrect()) { correctAnswerCounter.add(1); } } } catch (FinderException fex) { s_logger.log( Level.SEVERE, "Error getting answers distribution for test "+testId, fex); throw SchoolUtils.convertToEJBException(fex); } catch (RuntimeException ex) { s_logger.log( Level.SEVERE, "Error getting answers distribution for test "+testId, ex); throw ex; } SortedMap distMap = new TreeMap(); Iterator idxIter = tmpDistMap.keySet().iterator(); while( idxIter.hasNext() ) { Object idx = idxIter.next(); distMap.put(idx, new Integer(((IntegerType)tmpDistMap.get(idx)).getValue()) ); } return distMap; } /** * Gets the distribution of score percentages for all the questions in a test. * @param testId Test ID * @param type Type of percentages to calculate, determines the value to divide by, must be one of ReportGenerator.PERCENTAGE_BY_TEST or ReportGenerator.PERCENTAGE_BY_QUESTION. * @return SortedMap containing the question indices (Integer objects) as the keys and percentages (Double objects) as the values. */ public SortedMap getScorePercentageDistributionForTest(String testId, int type) { s_logger.fine("Getting score percentage distribution for test "+testId); Map quesScoreSumMap = new HashMap(); Map maxQuesScoreMap = (type==ReportGenerator.PERCENTAGE_BY_QUESTION) ? new HashMap() : null; int maxTestScore = 0; try { Collection historyCol = m_answerHistoryRecordHome.findByTest(testId); Iterator hIter=historyCol.iterator(); while (hIter.hasNext()) { LocalAnswerHistoryRecord record = (LocalAnswerHistoryRecord)hIter.next(); Integer quesIndex = new Integer(record.getQuestionIndex()); IntegerType quesScoreSum = (IntegerType)quesScoreSumMap.get( quesIndex); if (quesScoreSum==null) { quesScoreSum = new IntegerType(); quesScoreSumMap.put( quesIndex, quesScoreSum); } quesScoreSum.add( record.getUserScore() ); if (type==ReportGenerator.PERCENTAGE_BY_TEST) { maxTestScore += record.getQuestionScore(); } else if (type==ReportGenerator.PERCENTAGE_BY_QUESTION) { IntegerType maxQuesScore = (IntegerType)maxQuesScoreMap.get(quesIndex); if (maxQuesScore==null) { maxQuesScore = new IntegerType(); maxQuesScoreMap.put( quesIndex, maxQuesScore ); } maxQuesScore.add( record.getQuestionScore() ); } } } catch (FinderException fex) { s_logger.log( Level.SEVERE, "Error getting score percentage distribution for test "+testId, fex); throw SchoolUtils.convertToEJBException(fex); } catch (RuntimeException ex) { s_logger.log( Level.SEVERE, "Error getting score percentage distribution for test "+testId, ex); throw ex; } SortedMap distMap = new TreeMap(); Iterator quesIndexIter = quesScoreSumMap.keySet().iterator(); while ( quesIndexIter.hasNext() ) { Integer quesIndex = (Integer)quesIndexIter.next(); IntegerType quesScoreSumObj = (IntegerType)quesScoreSumMap.get( quesIndex ); int quesScoreSum = (quesScoreSumObj!=null) ? quesScoreSumObj.getValue() : 0; int divideBy = 0; if (type==ReportGenerator.PERCENTAGE_BY_TEST) { divideBy = maxTestScore; } else if (type==ReportGenerator.PERCENTAGE_BY_QUESTION) { IntegerType maxQuesScore = (IntegerType)maxQuesScoreMap.get(quesIndex); divideBy = (maxQuesScore!=null) ? maxQuesScore.getValue() : 0; } double percentage = (divideBy!=0) ? ((double)quesScoreSum*100.0/divideBy) : 0.0; distMap.put( quesIndex, new Double(percentage) ); } return distMap; } /** * Gets the distribution of overall score percentages for all users. * A user's overall percentage is calculated by divided the user's total score by his maximum possible score. * The percentages are grouped into categories with the specified range. For example, if categoryRange is * 22.0, the percentages are grouped into 0%-22%, 22%-44%, 44%-66%, 66%-88% and 88%-100% (the highest * category's limit is truncated to 100%). * @param categoryRange Range of a category. * @return SortedMap containing the upper-values of percentage categories (Double objects) as the keys and counts of users within a range (Integer objects) as the values. */ public SortedMap getScorePercentageDistributionByUsers(double categoryRange) { // Make sure categoryRange is not -ve, too small or too large. if ((categoryRange<0.01) || (categoryRange>99.99)) { throw new IllegalArgumentException("Invalid value "+categoryRange+" for categoryRange, must be between 0.01 and 99.99"); } // Need to calculate total scores for all users. // userTotalScoreMap stores the total scores for all users. Map userTotalScoreMap = new HashMap(); // userMaxScoreMap stores the maximum scores for all users. Map userMaxScoreMap = new HashMap(); try { Collection historyCol = m_answerHistoryRecordHome.findAll(); Iterator historyIter = historyCol.iterator(); while (historyIter.hasNext()) { LocalAnswerHistoryRecord record = (LocalAnswerHistoryRecord)historyIter.next(); String userId = record.getUserId(); IntegerType userTotalScore = (IntegerType)userTotalScoreMap.get(userId); if (userTotalScore==null) { userTotalScore = new IntegerType(); userTotalScoreMap.put( userId, userTotalScore); } userTotalScore.add( record.getUserScore() ); IntegerType userMaxScore = (IntegerType)userMaxScoreMap.get(userId); if (userMaxScore==null) { userMaxScore = new IntegerType(); userMaxScoreMap.put( userId, userMaxScore); } userMaxScore.add( record.getQuestionScore() ); } } catch (FinderException fex) { s_logger.log( Level.SEVERE, "Error getting score percentage distribution by users.", fex); throw SchoolUtils.convertToEJBException(fex); } catch (RuntimeException ex) { s_logger.log( Level.SEVERE, "Error getting score percentage distribution by users", ex); throw ex; } List highValueList = new ArrayList(); List distCountList = new ArrayList(); boolean finished = false; double highVal=categoryRange; while ( !finished ) { if (highVal>=100.00) { highVal = 100.00; finished = true; } highValueList.add( new Double(highVal) ); distCountList.add( new IntegerType() ); highVal+=categoryRange; } // Go through the users, calculate their percentages, and increment the appropriate categories. Iterator userIdIter = userTotalScoreMap.keySet().iterator(); int highValuesCount = highValueList.size(); while (userIdIter.hasNext()) { String userId = (String)userIdIter.next(); IntegerType userTotalScore = (IntegerType)userTotalScoreMap.get(userId); assert userTotalScore!=null : "Missing userTotalScore"; IntegerType userMaxScore = (IntegerType)userMaxScoreMap.get(userId); assert userMaxScore!=null : "Missing userMaxScore"; double percentage = (userMaxScore.getValue()>0) ? (userTotalScore.getValue()*100/userMaxScore.getValue()) : 0.0 ; Double categoryHighVal = null; for (int highValIndex=0; highValIndex < highValuesCount; highValIndex++) { Double highValD = (Double)highValueList.get(highValIndex); if (highValD.doubleValue() >= percentage ) { ((IntegerType)distCountList.get(highValIndex)).add( 1 ); break; } } } SortedMap distMap = new TreeMap(); for (int highValIndex=0; highValIndex < highValuesCount; highValIndex++) { distMap.put( highValueList.get(highValIndex), new Integer(((IntegerType)distCountList.get(highValIndex)).getValue()) ); } return distMap; } //----------------------------- // Container methods. //----------------------------- public void ejbCreate() {} public void ejbPostCreate() { } public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext sc) { m_context = sc; } private SessionContext m_context = null; private LocalTestHome m_testHome = null; private LocalQuestionHome m_quesHome = null; private LocalAnswerHistoryRecordHome m_answerHistoryRecordHome = null; private static Logger s_logger = Logger.getLogger( ReportGeneratorBean.class.getName()); }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -