⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 reportgeneratorbean.java

📁 老外的在线考试
💻 JAVA
字号:
/* * SchoolEJB - CyberDemia's library of EJBs for educational related services. * Copyright (C) 2004 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;import javax.ejb.*;import javax.naming.*;import java.util.*;import java.util.logging.*;import com.cyberdemia.value.*;import com.cyberdemia.ejb.BaseSessionBean;/** * ReportGeneratorBean is a session bean facade for retrieving and processing data * for reports based on historical records. * * @ejb.bean name="ReportGeneratorBean" *           type="Stateless" *           view-type="remote" *           jndi-name="ejb/ReportGenerator" * * @ejb.util generate="physical" * @ejb.interface remote-class="com.cyberdemia.school.ReportGenerator" extends="javax.ejb.EJBObject" * @ejb.home remote-class="com.cyberdemia.school.ReportGeneratorHome" extends="javax.ejb.EJBHome" * @ejb.ejb-ref ejb-name="AnswerHistoryRecordBean" ref-name="ejb/LocalAnswerHistoryRecord" view-type="local" * * @author Alexander Yap * @version $Revision: 1.7 $ at $Date: 2004/06/19 13:33:36 $ by $Author: alexycyap $ */public class ReportGeneratorBean extends BaseSessionBean{    public static final int PERCENTAGE_BY_TEST = 0;    public static final int PERCENTAGE_BY_QUESTION = 1;	/**	 * Gets a user's historical records for a test and user.	 *	 * @ejb.interface-method	 * @ejb.transaction type="Required"	 *	 * @param testId Test ID	 * @param userId User ID	 * @return List of AnswerHistoryData instances.	 */	public List getAnswerHistory(Integer testId, Integer userId) throws SchoolException	{		s_logger.fine("Getting answer history for test "+testId+", user "+userId);		LinkedList historyList = new LinkedList();		try		{			Collection historyCol = s_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.getQuestionType(),					record.getQuestionIndex(), record.getQuestionScore(),					record.getUserAnswer(), record.getCorrectAnswer(),					record.isAnswerCorrect(), record.getUserScore(),					record.getTimestamp()) 				);			}		}		catch (FinderException fex)		{			throw new SchoolException( "Error getting answer history for test "+testId+", user "+userId, fex);		}		catch (Exception ex)		{			throw new SchoolException( "Error getting answer history for test "+testId+", user "+userId, ex);		}		return historyList;	}	/**	 * Gets the distribution of users' answers for all the questions in a test.	 *	 * @ejb.interface-method	 * @ejb.transaction type="Required"	 *	 * @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(Integer testId) throws SchoolException	{		s_logger.fine("Getting answers distribution for test "+testId);		Map tmpDistMap = new HashMap();		try		{			Collection historyCol = s_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)		{			throw new SchoolException( "Error getting answers distribution for test "+testId, fex);		}		catch (Exception ex)		{			throw new SchoolException( "Error getting answers distribution for test "+testId, 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.	 *	 * @ejb.interface-method	 * @ejb.transaction type="Required"	 *	 * @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(Integer testId, int type) throws SchoolException	{		s_logger.fine("Getting score percentage distribution for test "+testId);		Map quesScoreSumMap = new HashMap();		Map maxQuesScoreMap = (type==PERCENTAGE_BY_QUESTION) ? new HashMap() : null;		int maxTestScore = 0;		try		{			Collection historyCol = s_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==PERCENTAGE_BY_TEST)				{					maxTestScore += record.getQuestionScore();				}				else if (type==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)		{			throw new SchoolException( "Error getting score percentage distribution for test "+testId, fex);		}		catch (Exception ex)		{			throw new SchoolException( "Error getting score percentage distribution for test "+testId, 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==PERCENTAGE_BY_TEST)			{				divideBy = maxTestScore;			}			else if (type==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%).	 *	 * @ejb.interface-method	 * @ejb.transaction type="Required"	 *	 * @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) throws SchoolException	{		// 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 = s_answerHistoryRecordHome.findAll();			Iterator historyIter = historyCol.iterator();			while (historyIter.hasNext())			{				LocalAnswerHistoryRecord record = (LocalAnswerHistoryRecord)historyIter.next();				Integer 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)		{			throw new SchoolException( "Error getting score percentage distribution by users.", fex);		}		catch (Exception ex)		{			throw new SchoolException( "Error getting score percentage distribution by users", 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())		{			Integer userId = (Integer)userIdIter.next();			IntegerType userTotalScore = (IntegerType)userTotalScoreMap.get(userId);			if (userTotalScore==null)			{				throw new SchoolException( "Missing userTotalScore for user ID "+userId);			}							IntegerType userMaxScore = (IntegerType)userMaxScoreMap.get(userId);			if (userMaxScore==null)			{				throw new SchoolException( "Missing userMaxScore for user ID "+userId);			}						double percentage = (userMaxScore.getValue()>0) ? (userTotalScore.getValue()*100/userMaxScore.getValue()) : 0.0 ;					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;	}    /**     * Dummy create method.     *     * @ejb.create-method view-type="remote"     */    public void ejbCreate()    {        // Nothing here    }	private static LocalAnswerHistoryRecordHome s_answerHistoryRecordHome = null;	static	{		try		{			Context ctx = new InitialContext();			try			{				s_answerHistoryRecordHome = (LocalAnswerHistoryRecordHome)ctx.lookup(JNDI_PREFIX+LocalAnswerHistoryRecordHome.JNDI_NAME);			}			finally			{				ctx.close();			}		}		catch (NamingException nex)		{			throw new EJBException("Error retrieving homes", nex);		}	}	private static Logger s_logger = Logger.getLogger( ReportGeneratorBean.class.getName());	} 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -