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

📄 questionmanagerbean.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.ejb.BaseSessionBean;/** * QuestionManager is a facade that provides useful methods for managing questions. * * @ejb.bean name="QuestionManagerBean" *           type="Stateless" *           view-type="remote" *           jndi-name="ejb/QuestionManager" * * @ejb.util generate="physical" * @ejb.interface remote-class="com.cyberdemia.school.QuestionManager" extends="javax.ejb.EJBObject" * @ejb.home remote-class="com.cyberdemia.school.QuestionManagerHome" extends="javax.ejb.EJBHome" * @ejb.ejb-ref ejb-name="QuestionBean" ref-name="ejb/LocalQuestion" view-type="local" * @ejb.ejb-ref ejb-name="AnswerChoiceBean" ref-name="ejb/LocalAnswerChoice" view-type="local" * * @author Alexander Yap * @version $Revision: 1.8 $ at $Date: 2004/06/20 16:05:17 $ by $Author: alexycyap $ * */public class QuestionManagerBean extends BaseSessionBean{	/**	 * Adds a new question to the database. 	 * Parameter answerChoicesDefined is provided to support a two-stage question creation	 * mechanism where the answer choices are only added in the latter stage. 	 * In this case, when the question is first created, the answer choices are not created,	 * and the question is marked as inactive.	 *	 * @ejb.interface-method	 * @ejb.transaction type="Required"	 *	 * @param data QuestionData instance with the data for the new question.	 * @param answerChoicesDefined true if answer choices are already defined, false if they are not yet defined. 	 * @return The unique ID of the new question.	 * @throws SchoolException if there is a problem creating the question.	 */	public Integer addQuestion(QuestionData data, boolean answerChoicesDefined) throws SchoolException	{		s_logger.log( Level.FINE, "Creating new Question name="+data.getName());		Integer id = null;		try		{			LocalQuestion ques = s_quesHome.create(				data.getName(), data.getQuestion(),				data.getAnswer(),				data.getHint(), data.getDifficulty(),				data.getExplanation(), data.getType(), 				data.getTimeLimitSeconds(), data.getScore(), 				answerChoicesDefined, data.isMustMatchAllKeywords() );						if (answerChoicesDefined && (data.isSingleChoiceType() || data.isMultipleChoiceType()) )			{				String[] answerChoices = data.getAnswerChoices();				for (int c=0; c<answerChoices.length; c++)				{					ques.addAnswerChoice( s_answerChoiceHome.create(c, answerChoices[c]) );				}			}			id = ques.getGeneratedPrimaryKey();			s_logger.log( Level.FINE, "New Question name="+data.getName()+" successfully created. Answers "+(answerChoicesDefined ? "already" : "not")+" defined.");		}		catch (CreateException cex)		{			getSessionContext().setRollbackOnly();			throw new SchoolException("Error creating Question "+data.getName(), cex);		}		return id;	}	/**	 * Deactives the specified question, after which it may be considered to 	 * be logically removed from the system.	 * This method may perform some checks first to ensure that the question	 * can be safely deactivated.	 *	 * @ejb.interface-method	 * @ejb.transaction type="Required"	 *	 * @param id Question ID	 * @return true if the question is deactivated, false if it is not (either a problem or it is already inactive) 	 * @throws SchoolException if the question can't be found.	 */	public boolean deactivateQuestion(Integer id) throws SchoolException	{		LocalQuestion ques =  null;		try		{			ques = s_quesHome.findByPrimaryKey(id);		}		catch (FinderException fex)		{			throw new SchoolException(SchoolException.QUESTION_NOT_FOUND, "Cannot find Question with ID "+id, fex);		}		boolean success = false;		try		{			ques.setLastModifiedMillis( System.currentTimeMillis() );			success = ques.deactivate();		}		catch (Exception ex)		{			getSessionContext().setRollbackOnly();			throw new SchoolException("Error deactivating Question with ID "+id, ex);		}		return success;	}	/**	 * Gets list of questions from database.	 *	 * @ejb.interface-method	 * @ejb.transaction type="Required"	 *	 * @param activeOnly true to only return active questions, false to return all questions.	 * @return Array of QuestionData instances.	 */		public QuestionData[] getQuestions(boolean activeOnly)	{		QuestionData[] dataArr = null;		try		{			Iterator quesIter = activeOnly ? s_quesHome.findAllActive().iterator() : s_quesHome.findAll().iterator();			ArrayList dataList = new ArrayList();			while (quesIter.hasNext())			{				LocalQuestion ques = (LocalQuestion)quesIter.next();				dataList.add( getDataFromQuestion(ques) );			}			dataArr = (QuestionData[])dataList.toArray(new QuestionData[0]);		}		catch (Exception ex)		{			// If there is a problem finding questions, just return empty array			dataArr = new QuestionData[0];		}		return dataArr;	}		/**	 * Gets Ids of active questions that belong to specified test.	 * If testId is null or an empty String, this methods gets all questions that 	 * are not assigned to any test.	 *	 * @ejb.interface-method	 * @ejb.transaction type="Required"	 *	 * @param testId Test Id	 * @return Array of QuestionData instances.	 */	public QuestionData[] getQuestionsByTest(Integer testId)	{		QuestionData[] dataArr = null;		try		{			Collection quesCol = null;            if (testId!=null)            {            	quesCol = s_quesHome.findByTest( testId );            }            else            {                quesCol = s_quesHome.findUnassignedToTest(true);            }			s_logger.fine("Retrieved "+quesCol.size()+" LocalQuestions.");			Iterator quesIter = quesCol.iterator();			ArrayList dataList = new ArrayList();			while (quesIter.hasNext())			{				LocalQuestion ques = (LocalQuestion)quesIter.next();				dataList.add( getDataFromQuestion(ques) );			}			dataArr = (QuestionData[])dataList.toArray(new QuestionData[0]);		}		catch (Exception ex)		{			// If there is a problem finding questions, just return empty array			dataArr = new QuestionData[0];		}		return dataArr;	}		/**	 * Gets the data of a specified question.	 *	 * @ejb.interface-method	 * @ejb.transaction type="Required"	 *	 * @param id Question ID.	 * @return QuestionData instance storing the question's data.	 * @throws SchoolException if the question can't be found.	 */	public QuestionData getQuestionData(Integer id) throws SchoolException	{		LocalQuestion ques =  null;		try		{			ques = s_quesHome.findByPrimaryKey(id);		}		catch (FinderException fex)		{			throw new SchoolException(SchoolException.QUESTION_NOT_FOUND, "Cannot find Question with ID "+id, fex);		}		QuestionData data = null;		try		{			data = getDataFromQuestion(ques);		}		catch (Exception ex)		{			throw new SchoolException( "Error getting data of Question with ID "+id, ex);		}		return data;	}	/**	 * Sets the data of a specified question.	 *	 * @ejb.interface-method	 * @ejb.transaction type="Required"	 *	 * @param id Question ID.	 * @param data QuestionData instance with the question's data.	 * @throws SchoolException if the question can't be found.	 */	public void setQuestionData(Integer id, QuestionData data) throws SchoolException	{		LocalQuestion ques =  null;		try		{			ques = s_quesHome.findByPrimaryKey(id);		}		catch (FinderException fex)		{			throw new SchoolException(SchoolException.QUESTION_NOT_FOUND, "Cannot find Question with ID "+id, fex);		}		try		{			ques.setName(data.getName());			ques.setContent( data.getQuestion());			ques.setHint(data.getHint());			ques.setDifficulty(data.getDifficulty());			ques.setExplanation(data.getExplanation());			ques.setTimeLimitSeconds(data.getTimeLimitSeconds());			ques.setLastModifiedMillis( System.currentTimeMillis() );			ques.setActive(data.isActive());			ques.setAnswer(data.getAnswer());			ques.setMustMatchAllKeywords(data.isMustMatchAllKeywords());			ques.setScore(data.getScore());			// The type cannot be changed for an existing question						if (data.isSingleChoiceType() || data.isMultipleChoiceType())			{				String[] answerChoices = data.getAnswerChoices();				for (int c=0; c<answerChoices.length; c++)				{					if (!ques.setAnswerChoiceText( c, answerChoices[c] ))					{						ques.addAnswerChoice( s_answerChoiceHome.create(c, answerChoices[c]) );					}				}							}					}		catch (Exception ex)		{			getSessionContext().setRollbackOnly();			throw new SchoolException( "Error setting data for Question with ID "+id, ex);		}	}    /**     * Dummy create method.     *     * @ejb.create-method view-type="remote"     */    public void ejbCreate()    {        // Nothing here    }	private QuestionData getDataFromQuestion(LocalQuestion ques)	{		QuestionData data = new QuestionData();		data.setId(ques.getId());		data.setName(ques.getName());		data.setQuestion(ques.getContent());		data.setAnswer(ques.getAnswer());		data.setHint(ques.getHint());		data.setType(ques.getType());		data.setScore(ques.getScore());		data.setDifficulty(ques.getDifficulty());		data.setExplanation(ques.getExplanation());		data.setCanDeactivate(ques.isActive() && (ques.getTest()==null));		data.setTimeLimitSeconds(ques.getTimeLimitSeconds());		data.setActive(ques.isActive());		data.setMustMatchAllKeywords(ques.isMustMatchAllKeywords());				if (data.isSingleChoiceType() || data.isMultipleChoiceType())		{			LocalAnswerChoice[] answerChoices = ques.getAnswerChoices();			String[] answerChoicesData = new String[answerChoices.length];			Arrays.fill(answerChoicesData, "");			for (int c=0; c<answerChoices.length; c++)			{				if (answerChoices[c]!=null)				{					answerChoicesData[answerChoices[c].getAnswerIndex()] = answerChoices[c].getAnswerText();				}			}			data.setAnswerChoices(answerChoicesData);		}		else		{			data.setAnswerChoices(null);		}		return data;	}	private static LocalQuestionHome s_quesHome = null;	private static LocalAnswerChoiceHome s_answerChoiceHome = null;	static	{		try		{			Context ctx = new InitialContext();			try			{				s_quesHome = (LocalQuestionHome)ctx.lookup(JNDI_PREFIX+LocalQuestionHome.JNDI_NAME);				s_answerChoiceHome = (LocalAnswerChoiceHome)ctx.lookup(JNDI_PREFIX+LocalAnswerChoiceHome.JNDI_NAME);			}			finally			{				ctx.close();			}		}		catch (NamingException nex)		{			throw new EJBException("Error retrieving homes", nex);		}	}	private static Logger s_logger = Logger.getLogger( QuestionManagerBean.class.getName());}

⌨️ 快捷键说明

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