Browse DevX
Sign up for e-mail newsletters from DevX


Unit Test Secured EJBs in Production : Page 3

Unit testing EJBs that are secured through permissions is complex. Learn how to unit test secured EJBs and EJB-based applications in the same production environment without needing to switch off the permission settings.


Create a Custom Servlet

Begin by creating the custom servlet code:
  1. Override the init method of the JUnitEEServlet servlet with the following code:
    public void init(ServletConfig config) throws ServletException {  
       	Hashtable env = new Hashtable();
       	env.put(Context.PROVIDER_URL, config.getInitParameter("PROVIDER_URL"));
      Context initialContext = null;
       	try {
      	initialContext = new InitialContext(env);
      	Object obj = initialContext.lookup("");
      } catch (NamingException e) {	
                  //programmatic log-in
       	LoginContext lc = null;
       	 try {
       	 	lc = new LoginContext("WSLogin",new WSCallbackHandlerImpl(config.getInitParameter("USER_ID"), _
    config.getInitParameter("PASSWORD"))); lc.login(); } catch (LoginException le) { System.out.println("Cannot create LoginContext. " + le.getMessage()); } catch(SecurityException se) { System.out.println("Cannot create LoginContext." + se.getMessage()); } subject = lc.getSubject(); }
  2. Override the runTests method of JUnitEEServlet with the following code:
      //running test cases in the WebSphere secure environment.
            protected TestRunnerResults runTests(String test, String[] testClassNames, HttpServletRequest _
    request, boolean forkThread) { final String iTest = test; final boolean bForkThread = forkThread; final String[] testNames = testClassNames; final HttpServletRequest fRequest = request; final TestRunnerResults results = new TestRunnerResults(); final TestRunner tester = new TestRunner(this.getDynamicClassLoader(), results, forkThread); try{ WSSubject.doAs(subject, new java.security.PrivilegedAction() { public Object run() { java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() { public Object run() { String id = fRequest.getSession().getId(); System.setProperty("sessionid",id); if (iTest == null) { if (bForkThread) { HttpSession session = fRequest.getSession(true); session.setAttribute(TESTRUNNER_KEY, tester); session.setAttribute(TESTRESULT_KEY, results); } tester.run(testNames); } else { tester.run(testNames[0], iTest); } return null; } }); return null; } }); } catch (Exception e) { e.printStackTrace(); } return results; }
  3. Override the service methods with the following:
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    super.doGet(request, response);  
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

Thanks for your registration, follow us on our social networks to keep up-to-date