Mocking HttpServletRequest to test Acegi-JSF

I’m a big fan of mock objects and enjoy playing with them. When working on the new release of my acegi-jsf components, I’ve written a couple of tests to check some stuff but realized that it was impossible to test the heart of the whole thing. The component Authorize has a dependendency to an IAuthenticationMode, there are 3 implementations of this interface; AllAuthenticationMode, AnyAuthenticationMode, NotAuthenticationMode each corresponds to component attributes ifAllGranted, ifAnyGranted, ifNotGranted. IAuthenticationMode has one method “isUserInRole(String roles, HttpServletRequest);”, each mode implements in their own way. Talking in patterns vocabulary; Strategy Pattern. Here is the IAuthenticationMode and the AllAuthenticationMode code(Other two are similiar).


IAuthenticationMode.java

  
  
  

    public interface IAuthenticationMode {
  public boolean isUserInRole(String roles, HttpServletRequest request);
}
  


AllAuthenticationMode.java

  
  
  

    public class AllAuthenticationMode implements IAuthenticationMode {

  public boolean isUserInRole(String roleList, HttpServletRequest request) {
    String [] roles = AcegiJsfUtils.parseRoleList(roleList);
    boolean isAuthorized = false;
    
    for (int i = 0; i < roles.length; i++) {
      if(request.isUserInRole(roles[i])) {
        isAuthorized = true;
      else {
        isAuthorized = false;
        break;
      }
    }
    return isAuthorized;
  }
}
  


Component’s class name is Authorize, this is the one with a dependency to an IAuthenticationMode and a HttpServletRequest. AuthenticationMode is set using the Tag class of the component. When component is called to encode it’s children, it checks whether the user satisfies the role requirements or not. If so, then it simply encodes the children. Following is the related part of Authorize.java.


Authorize.java

  
  
  

    public class Authorize extends UIComponentBase {
  private IAuthenticationMode authenticationMode;
  
  private HttpServletRequest request;
  
  public void encodeChildren(FacesContext contextthrows IOException {
    if (isUserInRole(getRoles())) {
      for (Iterator iter = getChildren().iterator(); iter.hasNext();) {
        UIComponent child = (UIComponentiter.next();
        encodeRecursive(context, child);
      }
    }
  }
  
  public boolean isUserInRole(String roles) {
    return getAuthenticationMode().isUserInRole(roles, getRequest());
  }
  
  public IAuthenticationMode getAuthenticationMode() {
    return authenticationMode;
  }

  public void setAuthenticationMode(IAuthenticationMode authenticationMode) {
    this.authenticationMode = authenticationMode;
  }
  
  private HttpServletRequest getRequest() {
    if(request == null)
      request = (HttpServletRequestFacesContext.getCurrentInstance().getExternalContext().getRequest();
    return request;
  }
  
  public void setRequest(HttpServletRequest request) {
    this.request = request;
}
  


So lets get back to the title of this entry, Mocking HttpServletRequest to test Acegi-JSF. If you check out the IAuthenticationMode implementations, each make a call to HttpServletRequest.isUserInRole(); method which was already wrapped by Acegi. So in order to test these implementations I’ve mocked HttpServletRequest and checked the outcomes. Here is the test of AllAuthenticationMode;


AuthorizeTester.java

  
  
  

    public class AuthorizeTester extends MockObjectTestCase {

  private Authorize authorize;
  
  private IAuthenticationMode authenticationMode;
  
  Mock mockRequest;
  
  private String roles;
  
  public void setUp() {
    authorize = new Authorize();
    mockRequest = new Mock(HttpServletRequest.class);
    authorize.setRequest((HttpServletRequestmockRequest.proxy());
    roles = "A,B, C";
  }
  
  public void testAllAuthenticationModeReturnsFalseWhenUserSatisfiesFirstTwoRolesButNotTheLastOne() {
    authorize.setAuthenticationMode(new AllAuthenticationMode());
    mockRequest.expects(once()).method("isUserInRole").with(eq("A")).will(returnValue(true));
    mockRequest.expects(once()).method("isUserInRole").with(eq("B")).will(returnValue(true));
    mockRequest.expects(once()).method("isUserInRole").with(eq("C")).will(returnValue(false));
    boolean isUserInRole = authorize.isUserInRole(roles);
    assertEquals(isUserInRole, false);
  }
  
  public void testAllAuthenticationModeReturnsTrueWhenUserSatisfiesAllOfTheRoles() {
    authorize.setAuthenticationMode(new AllAuthenticationMode());
    mockRequest.expects(once()).method("isUserInRole").with(eq("A")).will(returnValue(true));
    mockRequest.expects(once()).method("isUserInRole").with(eq("B")).will(returnValue(true));
    mockRequest.expects(once()).method("isUserInRole").with(eq("C")).will(returnValue(true));
    boolean isUserInRole = authorize.isUserInRole(roles);
    assertEquals(isUserInRole, true);
  }
}
  

The role list is “A,B, C”, I test the condition where the ifAllGranted is supplied with this list. Then I set expectations on request for each of the roles. For example, in first test, user is in role A,B but not in C. Also as a test lunatic myself, I did not forget to write the simple test of the function that takes a role list seperated with commas and whitespaces and returns a string array whose elements will be checked in isUserInRole(String role). Yes this is an easy test but I had a lot of pain after I’ve missed a test case.


AcegiJsfUtils.java

  
  
  

    public class AcegiJsfUtils {

  public static String[] parseRoleList(String roles) {
    String [] roleArray =  roles.split(",");
    for (int i = 0; i < roleArray.length; i++) {
      roleArray[i= roleArray[i].trim();
    }
    return roleArray;
  }
}
  

AcegiJsfUtilsTester.java

  
  
  

    public class AcegiJsfUtilsTester extends TestCase {

  public void testRoleListParsingRunsOkWhenThereAreWhitespacesEverywhere() {
    String roleString = "ROLE_A ,   ROLE_B ,     ROLE_C";
    String [] roles = AcegiJsfUtils.parseRoleList(roleString);
    assertEquals(roles.length, 3);
    assertEquals(roles[0],"ROLE_A");
    assertEquals(roles[1],"ROLE_B");
    assertEquals(roles[2],"ROLE_C");
  }
}
  

There are more tests, I’ve just posted some of them as an example but all can be found at myFaces jsf-comp repository at sourceforge. In addition as I mentioned before I’ve refactored my code in order to make it suitable for testing, I believe this is yet another advantage that testing brings to your code. To end with something cool; “Testing leads to better code, not just safer”.

Posted in Java. 1 Comment »

"PRO JSF and AJAX" book review

I was eagerly waiting for my shipment bringing me this book; “PRO JSF and AJAX”.  It was hell of a busy weekend however I’ve created some time to read it. I am writing this review after reading several chapters.

The topic is “PRO JSF and AJAX”, the difference from the other JSF books out there is, “this one is not for newbies”. I think this is the first jsf book ever created not for beginners. One of the things I like most is that, the book also covers JSF 1.2, it refers to the previous versions however mentions the changes in JSF 1.2, cool stuff!

Main focus is on custom component development, first chapter begins with the explaining deepest details of JSF and it jumps directly to the component stuff. Well, if you have read my blog before, you should know that I like writing custom components; JSF Chart Creator, Acegi-JSF, JSF Client Side Validators, JSF DHTML Component Tree and etc. Following is very important, if you are not interested in custom component development then this book is not necessary for you however if you like implementing custom components then this book is definitely a must.

Finally, about the authors, Jonas Jacobi and John Fallows. These Oracle people are experts in JSF and involved in ADF faces. I know some guy preordered the book just after checking the authors.

Posted in Java. 1 Comment »

How to do Pair Programming "By Yourself"

I’ve observed some code written by some guy in my day job and definitely this guy is doing pair programming although “he has no pair”. For example there is a method with 4-5 lines of code, the comment above it is generally 9-10 lines. It seems “Comment-Driven Development” is applied in this case. The interesting thing is when you read through the code, more comes out because the comment actually seems like a documentation of a dialog between two pairs. Like this one, just translated; Believe it or not it is real.

//This method is used for getting a collection of an entity in http session.
// It seems to be working, I should apply more cases.

// No! this method should not be located here, I’ve observed a utility for it in our utils package
// Let this one still be located here, I will remove it later after some more blah blah.

Here are some new practices I could derive from these,

1) Comment-Driven Development
2) Comment-First Design
3) Solo pair programming

Getter-Setter Generator Plugin

We are generating both of the code and the hibernate mappings from uml diagrams however IBM’s modeller does not generate accessors. In order to solve this problem, a new plugin was born. It has cool features like selecting multiple packages containing the classes that need their accessors to be generated. My colleague Mert has refactored and open-sourced it, you can check out the details at his place.

Posted in Java. 1 Comment »

JSF Component Tree as a Real DHTML Tree

JSF components are managed using a conceptual tree data structure which is one of the core elements of the framework. Both Sun RI and myFaces provide utility methods to print the tree using a printstream, also I’ve observed people creating their own algorithms to output the expanded tree to a printstream generally System.out.

Me and my colleague are working on a library that will provide traceability features for the jsf applications and on the way I’ve thought it would be cool to view and traverse the component tree as a DHTML tree in the page containing the components. Well, the tree is ready now, it contains  several types of informations like id, rendered and etc. If the component implements ValueHolder, value is also displayed in the tree, there may be possible additions to these like component type and also I am planning to remove the rendered attribute since it does not vary much. So enough of text, here are some screenshots,

Free Image Hosting at www.ImageShack.us Free Image Hosting at www.ImageShack.us Free Image Hosting at www.ImageShack.us
I’ve created a custom component to represent this tree on a page, currently it is used as &lt;ft:trace showTree=”true”/&gt; I’ve used one of the tree scripts from dynamicdrive and change some parts. Using a recursive tree traversing algorithm, the custom component populates the dhtml tree. Components with children are represented bold and when they are clicked each child is displayed as a leaf, on the other hand if there is no child, the leaf is not clickable.

Posted in Java. 4 Comments »

One million dollar JSF Puzzle

Following puzzle came up to my mind yesterday when I was working on a new library that hopefuly will bring some traceability features to JSF. Here is the question:

Roni wants to measure how long each phase in the JSF lifecycle takes and then a custom component he has planned to implement will display the results on a page. In each phase, he saves the time at beforePhase and afterPhase methods, but when the case is RenderResponse phase, he realizes a deadend. The component cannot get the time after render response phase because component itself(the info it has collected so far) is already rendered in the render response phase. So what should he do to measure how long render response phase takes and render it to the page correctly?

One solution is a bit tricky, the component renders something special (buffered by JSF) that will be replaced at after render response phase. When jsf calls afterPhase method of the render response phaselistener, Roni takes the scene; first gets the time then replaces the measured time with the special token in the response buffer using string tricks. He actually does filtering in the render response phase listener. When the response reaches the client, whole info will be correctly displayed.

Posted in Java. 5 Comments »