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

📄 cybertesterutils.java

📁 老外的在线考试
💻 JAVA
字号:
/* * CyberTester - J2EE Web application for creating, delivering and managing tests/exams/surveys.  * Copyright (C) 2003 CyberDemia Research and Services Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program (see the file COPYING); 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 program for complete text of license. */package com.cyberdemia.cybertester;import com.cyberdemia.school.*;import com.cyberdemia.user.*;import javax.servlet.*;import javax.servlet.http.*;import javax.naming.*;import javax.rmi.PortableRemoteObject;import org.apache.struts.action.*;import java.util.logging.*;/** *  * CyberTesterUtils is a utility class that defines useful static utility methods. *  * @author Alexander Yap */public abstract class CyberTesterUtils{	private static Logger s_logger = Logger.getLogger("com.cyberdemia.cybertester");	private static QuestionManagerHome s_quesMgrHome = null;	private static TestManagerHome s_testMgrHome = null;	private static UserManagerHome s_userMgrHome = null;	private static ReportGeneratorHome s_reportGeneratorHome = null;	static	{		initManagers();	}	/**	* Gets logger for CyberTester server-side code.	*/	public static Logger getLogger()	{	    return s_logger;	}	/**	 * Gets home interface for QuestionManager.	 * @return Home interface for QuestionManager.	 */	public static QuestionManagerHome getQuestionManagerHome()	{		return s_quesMgrHome;	}	/**	 * Gets home interface for TestManager.	 * @return Home interface for TestManager.	 */	public static TestManagerHome getTestManagerHome()	{		return s_testMgrHome;	}	/**	 * Gets home interface for UserManager.	 * @return Home interface for UserManager.	 */	public static UserManagerHome getUserManagerHome()	{		return s_userMgrHome;	}	/**	 * Gets home interface for ReportGenerator.	 * @return Home interface for ReportGenerator.	 */	public static ReportGeneratorHome getReportGeneratorHome()	{		return s_reportGeneratorHome;	}	/**	* Gets the session if it is valid for currently logged in user.	* If the session is not found, timed-out, or missing login data,	* it is considered invalid. This method returns null if session is invalid.	*	* @param request Request to extract session from.	* @return Valid user session, or null if session is invalid.	*/	public static HttpSession getUserSession( HttpServletRequest request ) throws ServletException	{		HttpSession session = request.getSession(false);		if (session==null)			return null;		Object userLogin = session.getAttribute(Constants.USER_LOGIN_KEY);		Object userId = session.getAttribute(Constants.USER_ID_KEY);		if ((userLogin==null) || (userId==null) )		{			return null;		}		if (!userLogin.equals(request.getRemoteUser()))		{			throw new ServletException("User mismatch, expecting "+userLogin+", but got "+request.getRemoteUser());		}		return session;	}	private static void initManagers()	{		Context ctx = null;		Object homeObj = null;		try		{			ctx = new InitialContext();		}		catch (Exception ex)		{			throw new RuntimeException("Error creating InitialContext.",ex);		}		try		{			homeObj = ctx.lookup("java:comp/env/ejb/questionManager");			s_quesMgrHome = (QuestionManagerHome)PortableRemoteObject.narrow(homeObj, QuestionManagerHome.class);		}		catch (Exception ex)		{			throw new RuntimeException("Error initializing QuestionManagerHome.",ex);		}				try		{			homeObj = ctx.lookup("java:comp/env/ejb/testManager");			s_testMgrHome = (TestManagerHome)PortableRemoteObject.narrow(homeObj, TestManagerHome.class);		}		catch (Exception ex)		{			throw new RuntimeException("Error initializing TestManagerHome.",ex);		}				try		{			homeObj = ctx.lookup("java:comp/env/ejb/userManager");			s_userMgrHome = (UserManagerHome)PortableRemoteObject.narrow(homeObj, UserManagerHome.class);		}		catch (Exception ex)		{			throw new RuntimeException("Error initializing UserManagerHome.",ex);		}		try		{			homeObj = ctx.lookup("java:comp/env/ejb/reportGenerator");			s_reportGeneratorHome = (ReportGeneratorHome)PortableRemoteObject.narrow(homeObj, ReportGeneratorHome.class);		}		catch (Exception ex)		{			throw new RuntimeException("Error initializing ReportGeneratorHome.",ex);		}	}		/**	 * Gets the data of tests under a owner hierarcy node.	 * @param ownerHierId Owner hierarchy ID, or null to return all tests.	 * @param activeOnly true to return only active tests, false to consider all tests.	 * @return Array of TestData instances, or empty array if there is an error.	 */	public static TestData[] getTestsData(String ownerHierId, boolean activeOnly)	{		TestData[] testDataArr = null;		try		{			TestManager testMgr = (TestManager)s_testMgrHome.create();			testDataArr = testMgr.getTests(ownerHierId, activeOnly);		}		catch (Exception ex)		{			s_logger.log( Level.SEVERE, "Error getting tests for ownerHeirId "+ownerHierId, ex);			testDataArr = new TestData[0];		}		return testDataArr;			}		/**	 * Gets the data of tests, under a owner hierarchy node, that have been assigned to a user.  	 * @param ownerHierId Owner hierarchy ID	 * @param userId User ID	 * @return Array of TestData instances, or empty array if there is an error.	 */	public static TestData[] getTestsDataForUser(String ownerHierId, String userId)	{		TestData[] testDataArr = null;		try		{			TestManager testMgr = (TestManager)s_testMgrHome.create();			testDataArr = testMgr.getTestsForUser( ownerHierId, userId);		}		catch (Exception ex)		{			s_logger.log( Level.SEVERE, "Error getting tests for ownerHeirId "+ownerHierId+", user "+userId, ex);			testDataArr = new TestData[0];		}		return testDataArr;			}	/**	 * Gets the data of tests, under a owner hierarchy node, that are <b>not</b> assigned to a user.  	 * @param ownerHierId Owner hierarchy ID	 * @param userId User ID to exclude.	 * @return Array of TestData instances, or empty array if there is an error.	 */	public static TestData[] getTestsDataForNotUser(String ownerHierId, String userId)	{		TestData[] testDataArr = null;		try		{			TestManager testMgr = (TestManager)s_testMgrHome.create();			testDataArr = testMgr.getTestsForNotUser( ownerHierId, userId);		}		catch (Exception ex)		{			s_logger.log( Level.SEVERE, "Error getting tests for ownerHeirId "+ownerHierId+", EXCLUDING user "+userId, ex);			testDataArr = new TestData[0];		}		return testDataArr;			}		/**	 * Convenience method to first search for a request parameter with the	 * specified key. If this parameter is not present, search for a	 * request attribute (of type String) with the same key.	 * @param request Request from client.	 * @param key Key to search request parameter and attribute for.	 * @return Parameter or attribute String value, or null if the key is not present in both request parameter or attribute.	 */	public static String getParameterOrRequestAttribute(HttpServletRequest request, String key)	{		String val = request.getParameter(key);		if (val==null)		{			val = (String)request.getAttribute(key);		}		return val;	}		/**	 * Performs validation on a form parameter to ensure that it has a numeric value.	 * @param paramName Parameter name for logging and error reporting purposes.	 * @param value The parameter value to be validated.	 * @param errors ActionErrors instance to store any errors.	 * @return true if the form parameter has a valid numeric value.	 */	public static boolean validateRequiredFormNumericParam(String paramName, String value, ActionErrors errors)	{		boolean success = true;		if ((value == null) || (value.length() < 1))		{			errors.add(paramName, new ActionError("error.form.missingParam.enter",paramName));			success = false;		}		else		{			try			{				Double.parseDouble(value);			}			catch (NumberFormatException nfex)			{				errors.add(paramName, new ActionError("error.form.nonNumericParam",paramName,value));				success = false;			}		}		return success;	}	/**	 * Performs validation on a form parameter to ensure that it has an integer value.	 * @param paramName Parameter name for logging and error reporting purposes.	 * @param value The parameter value to be validated.	 * @param negativeAllowed true to allow negative integers to be treated as valid, false to treat negative integers as invalid.	 * @param errors ActionErrors instance to store any errors.	 * @return true if the form parameter has a valid integer value.	 */	public static boolean validateRequiredFormIntegerParam(String paramName, String value, boolean negativeAllowed, ActionErrors errors)	{		boolean success = false;		if ((value == null) || (value.length() < 1))		{			errors.add(paramName, new ActionError("error.form.missingParam.enter",paramName));		}		else if (value.indexOf(".")>=0)		{			try			{				int intVal = Integer.parseInt(value);				if ( negativeAllowed || (intVal>=0) )				{					success = true;				}				else				{					errors.add(paramName, new ActionError("error.form.negativeIntegerParam",paramName,value));				}			}			catch (NumberFormatException nfex)			{				errors.add(paramName, new ActionError("error.form.nonIntegerParam",paramName,value));			}		}		else		{			errors.add(paramName, new ActionError("error.form.nonIntegerParam",paramName,value));		}		return success;	}	/**	 * Performs validation on a form parameter to ensure that it has an numeric value within a given range.	 * @param paramName Parameter name for logging and error reporting purposes.	 * @param value The parameter value to be validated.	 * @param lower Lower limit of the range (inclusive).	 * @param upper Upper limit of the range (inclusive).	 * @param errors ActionErrors instance to store any errors.	 * @return true if the form parameter has a valid numeric value within the range.	 */	public static boolean validateRequiredFormNumericParamInRange(String paramName, String value, double lower, double upper, ActionErrors errors)	{		boolean success = true;		success = validateRequiredFormNumericParam(paramName, value, errors);		if (success)		{			double val = Double.parseDouble(value);			if ((val<lower) || (val>upper))			{				errors.add(paramName, new ActionError("error.form.outOfRangeNumericParam",paramName,value,String.valueOf(lower),String.valueOf(upper)));				success = false;			}		}		return success;	}	/**	 * Performs validation on a form parameter to ensure that it exists and is not an empty String.	 * This form parameter value is entered from a text-field in the GUI.	 * @param paramName Parameter name for logging and error reporting purposes.	 * @param value The parameter value to be validated.	 * @param errors ActionErrors instance to store any errors.	 * @return true if the form parameter has a valid integer value.	 */	public static boolean validateRequiredFormEnteredParam(String paramName, String value, ActionErrors errors)	{		return validateRequiredFormParam(paramName, value, errors, "error.form.missingParam.enter");	}		/**	 * Performs validation on a form parameter to ensure that it exists and is not an empty String.	 * This form parameter value is selected from a multi-value selector in the GUI.	 * @param paramName Parameter name for logging and error reporting purposes.	 * @param value The parameter value to be validated.	 * @param errors ActionErrors instance to store any errors.	 * @return true if the form parameter has a valid integer value.	 */	public static boolean validateRequiredFormSelectedParam(String paramName, String value, ActionErrors errors)	{		return validateRequiredFormParam(paramName, value, errors, "error.form.missingParam.select");	}		/**	 * Performs validation on a form parameter to ensure that it exists and is not an empty String.	 * @param paramName Parameter name for logging and error reporting purposes.	 * @param value The parameter value to be validated.	 * @param errors ActionErrors instance to store any errors.	 * @param errMsgKey Key to Struts error message resource to be used as error message.	 * @return true if the form parameter has a valid integer value.	 */	private static boolean validateRequiredFormParam(String paramName, String value, ActionErrors errors, String errMsgKey)	{		boolean success = true;		if ((value == null) || (value.length() < 1))		{			errors.add(paramName, new ActionError(errMsgKey,paramName));			success = false;		}		return success;	}}

⌨️ 快捷键说明

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