5.4 Understanding the Custom Rule Class Example

The following example explains how to create a custom rule class:

import java.util.Base64;
import java.util.Map;
import java.util.Properties;
import com.novell.nam.nidp.risk.context.DeviceContext;
import com.novell.nam.nidp.risk.context.HTTPContext;
import com.novell.nam.nidp.risk.context.LocationContext;
import com.novell.nam.nidp.risk.context.UserContext;
import com.novell.nam.nidp.risk.core.rules.Rule;
import com.novell.nam.nidp.risk.util.ResponseObject;
public class CustomRuleTmpl extends Rule {
  /**
   * @param configProps
   * All the configuration will be passed to the constructor.
   * 
   * Pass the type of user historical data you want.
   * 
   */
public CustomRuleTmpl(Properties configProps) {super(configProps);    
/*
 * Check all the properties that is configured
*/
      printProperties(configProps);
    if ( isHistoricalDataEnabled())
      {
     
// Enter all the user attributes that you need from the history database. Generally you would need one or two values.      setType(HistoricalAttributeEntries.IP.name());
/*
* The following commented code shows how to get other historical data from database.
*   setType(HistoricalAttributeEntries.LASTLOGGEDINTIME.name());
*   setType(HistoricalAttributeEntries.CITY.name())
*   setType(HistoricalAttributeEntries.COUNTRY.name());
*   setType(HistoricalAttributeEntries.REGION.name());
*   setType(HistoricalAttributeEntries.RISKSCORE.name());
*   setType(HistoricalAttributeEntries.LOGINRESULT.name());
*   setType(HistoricalAttributeEntries.RISKCATEGORY.name());
*   setType(HistoricalAttributeEntries.RISKSCORE.name());
*   setType(HistoricalAttributeEntries.REGIONCODE.name());
*   setType(HistoricalAttributeEntries.METROCODE.name());
*   setType(HistoricalAttributeEntries.POSTCODE.name());
     *
     *
     * Or you could even set it using an array List
     *   clearType(); // Clear the previously set rule type values
   *  ArrayList<String> historyAttributes = newArrayList<String>();
   *  historyAttributes.add ( HistoricalAttributeEntries.IP.name());
   * historyAttributes.add (HistoricalAttributeEntries.LASTLOGGEDINTIME.name());
   *  setType(historyAttributes);
   */      
    }  
  }
private void printProperties(Properties configProps) {
    System.out.println("Configured properties are: -");
        for (Entry<Object, Object> e: configProps.entrySet())
    System.out.println("Name :" + e.getKey() + "Value : " + e.getValue());
}
/* (non-Javadoc)
   * @see com.novell.nam.nidp.risk.core.rules.Rule#evaluate(com.novell.nam.nidp.risk.context.HTTPContext,
com.novell.nam.nidp.risk.context.LocationContext, com.novell.nam.nidp.risk.context.DeviceContext,
com.novell.nam.nidp.risk.context.UserContext, com.novell.nam.nidp.risk.util.ResponseObject)
   *
   * This method evaluates the rule and is called in the order of the priority.
   * 
   * Parameters 
   * HttpContext- Contains all the request http header information
   * LocationContext- Contains information about the client location (IP)
   * DeviceContext- Contains device information
   * UserContext- Contains user information that includes user attributes, roles, and historical login data of the user.
   *   ResponseObject- Can be used for setting cookies, headers and user attributes on completion of the risk calculation.
   * 
     * Return Values
   * true- on successful evaluation of the rule.
   * false- if failed to evaluate the rule. In this case, configured risk score is considered.
    *   
  *   This method will have 3 sections
  * 1) Pre-evaluation: To get all the parameters of the user login
  * 2)Evaluate the rule: Apply the use case to the evaluation using the parameters
  * 3)Post-evaluation: - Set result, cookie and history parameters if needed
   */

@Override
    public boolean evaluate(HTTPContext httpContext, LocationContext
    lContext,      DeviceContext dContext, UserContext uContext,
    ResponseObject rspObject) {
    boolean returnValue = false;
    if ( isRuleEnabled())
      {
      /* ######## Pre-Evaluation Section #####################*/
      getHTTPHeaderInformation(httpContext);
      getCookieInformation(httpContext, "JSESSIONID");
      getLocationParameter(lContext);
      getUserContext(uContext);
      /* ############### Evaluation Section ####################*/
      { 
        /*
         * Change the return value according logic of the evaluation
         */
if ( true )
             returnValue = true;
        }
      /* ############### Post-Evaluation Section ####################*/
      /*
 * Execute the post evaluation method to consider other configuration like negate result
       */
//  rspObject.setUserAttr(HistoricalAttributeEntries.IP.name(), clientIP);
  
 return getReturnValue(returnValue); 
          }
    return true;
    }
      
    /*
   * Get all the user context/attributes
   */
    private void getUserContext(UserContext uContext) {
      // TODO Auto-generated method stub
    getUserAttribute(uContext);
    getUserRoles(uContext);
    getHistoricalData(uContext);
  }
  /*
   * Get the historical data of the user from the configured database
   */
    private void getHistoricalData(UserContext uContext) {
    // It will get all the passed transaction for the user in the past.
    // If the transaction you looking for is not found, that mean it has failed for that log in.
    HistoryRecord records = (HistoryRecord)uContext.get(HistoricalAttributeEntries.IP.name());
    if ( records != null)
      {  
      System.out.println("Printing past entries from the History, in this example its the IP used by the user");
      for( Object o : records.getValue() )
              System.out.println("< " + (String)o + "
>\n");
    }
    }
  /*
     * Get the user's current role information
     */
      private void getUserRoles(UserContext uContext) {
String[] values = (String[])
uContext.get(UserProfile.Constants.ROLES.name());
    System.out,println("Roles of the user are ");
      for ( String role : values)
      System.out,println(" " + role + ",");
    }
  /*
  * Get the user's ldap attributes.
      * 
  * NOTE: To get attributes here, you must return the name of the attributes, you need, using method getRequiredAttributes();

   */
     private void getUserAttribute(UserContext uContext) {
   // Value will be null if attribute name is not set as part of getRequiredAttributes()
    String mail = (String) uContext.get("mail");
    String carlicense = (String) uContext.get("carlicense");
    System.out.println("Mail attribute of the user is " + mail + ",
and the carlicense is " + carlicense);
  }
/*
* This method should return the name of the user ldap attributes required during evaluation of the rule. You can configure those in the custom rule properties and can pass the value here.
   */
     @Override
     public String[] getRequiredAttributes() {
         // TODO Auto-generated method stub
         String[] attributes = new String[2];
    attributes[0] = "mail";
      attributes[1] = "carlicense";
      return attributes;
    }
  /*
  * Get the location parameter of the user
    * 
  */
  private void getLocationParameter(LocationContext lContext) {
    String clientIP = lContext.getClientIPAddress();
      System.out,println("Client Ip address for this request is = " + clientIP);    
    Properties props = new Properties();
      Provider provider;
   
       try {
       provider = GeoLocationFactory.getProvider
       RiskEngine.getInstance().getCoreProps().getProperty("geolocation.provider"),
    null, props);
      GeoLocBean geoLoc = provider.readGeoLocInfo(InetAddress
            .getByName(clientIP));
      System.out.println("Country  = " + geoLoc.getCountry());
        System.out.println("Country code = " + geoLoc.getCountryCode());
        System.out.println("City  = " + geoLoc.getCity());
        } catch (GeoLocException | UnknownHostException
e) {
      // TODO Auto-generated catch block
          System.out.println("Geo location configuration exception
" + e.getLocalizedMessage());
      e.printStackTrace();
          }
  }
  /*
   * Get a specific cookie out of headers
       */
      private void getCookieInformation(HTTPContext httpContext,
String cookieName) {
    String cookieValue = httpContext.getCookieValue(cookieName);
    System.out,println("Cookie Name = " + cookieName + "
Value = " + cookieValue);
 }
/*
       * Get all http Context information.
     * Contains all http headers that is part of the request, including cookies.
   */ 
     private void getHTTPHeaderInformation(HTTPContext httpContext) {
      Map<String, String> headers = httpContext.getM_HTTPHeaders();
      Iterator itr = headers.entrySet().iterator();
      for  ( Map.Entry< String, String> entry : headers.entrySet()
)
        System.out,println("Header Name = " + entry.getKey()
 + " Value = " + entry.getValue());
  }
}