Previous Topic: Sample CodeNext Topic: Java API Reference


Sample Code for Risk Evaluation and Post-Evaluation

You can plug the following sample code snippet in to your application code to test the risk evaluation and post-evaluation functionality of RiskFort.

/* Packages to be imported for RiskFort Transaction API */

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.HashMap;

import com.arcot.riskfortAPI.DeviceContext;
import com.arcot.riskfortAPI.LocationContext;
import com.arcot.riskfortAPI.PostEvaluateResponse;
import com.arcot.riskfortAPI.RiskAssessment;
import com.arcot.riskfortAPI.RiskException;
import com.arcot.riskfortAPI.RFSDKException;
import com.arcot.riskfortAPI.RiskFactory;
import com.arcot.riskfortAPI.RiskXActionAPI;
import com.arcot.riskfortAPI.TransactionContext;
import com.arcot.riskfortAPI.UserContext;
import com.arcot.riskfortAPI.AdditionalInputs;

public class Assess_Risk {

// In this example values are hard coded for sample use.
public static void main(String[] args) {
  /*
  initialize:
    Initializes API object from the input property file.
    initialize() should be called only once at the application startup.

    Following are the fields and format of the property file.
      HOST.1=RiskFort server IP address
      PORT.1=RiskFort server port number
      TRANSPORT_TYPE = Connection Type. Possible values are TLS/TCP
      CA_CERT_FILE = Required if TRANSPORT_TYPE = TLS: CA certificate file. server CA certificate (in PEM format) file path.

  public static synchronized void initialize(String propertyLocation)
    throws IOException, RiskException;

  Parameters:
      propertyLocation - Represents the location to be passed as a parameter with respect to the class path.
      If <code>null</code> is passed, it will take default location is properties/riskfort.risk-evaluation.properties.
  Returns:

  Throws:
    RiskException - If request fails for any reason.
    IOException
  */


  // Sample code to initialize the API object from the input property file.
  // Create a RiskXActionAPI object.
  RiskXActionAPI api = null;

  String propertiesFileLocation = "/properties/riskfort.risk-evaluation.properties";

  try {
      System.out.println("Initializing RiskFort API using " + propertiesFileLocation);

    // Initializes RiskXActionAPI object from the input property file.
      RiskFactory.initialize(propertiesFileLocation);
      //  Get RiskXActionAPI object that has been initialized earlier.
      api = RiskFactory.getRiskXActionAPI();

      System.out.println("RiskFort API initialized.");
  }
  catch (IOException e) {
    // Take suitable action.

  }
  catch (RFSDKException e) {

    /* The following methods on UserRepositoryException object can be used to get the error codes and error messages as follows:
    * String code = e.getErrorCode();
    * String message = e.getMessage();
    */
    System.out.println("Exception during initialize.");
    /* System.out.println("Error code: " + e.getErrorCode()); */
    System.out.println("Error message: " + e.getMessage());

    /* The following error codes are returned by the API. */

    /* ERRCODE_INVALID_INPUT
    * This can be caused due to two reasons.
    * 1. Possible Reason:
    *    The transport type mentioned in the properties file is invalid.
    *    Possible Action:
    *     Mention the valid transport type in the "riskfort.risk-evaluation.properties" file.
    * 2. Possible Reason:
    *    If TRANSPORT_TYPE=TLS in the properties file, the primary key file used for TLS was not found.
    *    Possible Action:
    *     Check for the correctness of the path to the primary key file.
    */

    /* ERRCODE_RISKXACTIONAPI_ALREADY_INITIALIZED
    * Possible Reason:
    *    The API being initialized has already been initialized.
    * Possible Action:
    *   Get the RiskXActionAPI object and continue with the transaction.
    */

    /* ERROR_CONF_INVALID_POOL
    * Possible Reason:
    *  Inability to create a pool of live connections to RiskFort Server.
    * Possible Action:
    *
    */

    /* ERROR_CONF_NOT_AVAILABLE
    * This can be caused due to two reasons.
    * 1. Possible Reason:
    *    The properties file could not be read.
    *    Possible Action:
    *     Check for the correctness of the path to the properties file.
    * 2. Possible Reason:
    *    The Root CA for the server certificate is invalid.
    *    Possible Action:
    *     Get a valid server certificate.
    */
  }


  /*
  evaluateRisk:
    Evaluates risk associated with the transaction and returns an advice accordingly. It also provides a new DeviceId.
    Actions to be taken by the calling application are:
      1. The output DeviceId should be stored on the user machine in some form. Most common way is to store it as a HTTP cookie. Nevertheless, storing it as a HTTP cookie has the risk of it being deleted when user deletes all cookies on the machine.
      2. Retrieve the DeviceId from user machine and set it using setDeviceID.
      3. If RiskAdvice is equal to INCREASEAUTH, perform second authentication and pass the result of the second authentication to RiskFort using PostEvaluate.

  public RiskAssessment evaluateRisk(java.lang.String callerId,
        DeviceContext deviceContext,
        LocationContext locationContext,
        UserContext userContext,
        TransactionContext transactionContext,
        AdditionalInputs additionalInputs)
     throws RiskException

  Parameters:
    callerId - An identifier as decided by the application calling the API for it's own tracking.
    deviceContext - Device contextual information.
    locationContext - Location contextual information(IP address).
    userContext - User contextual information.
    transactionContext - Transaction contextual information.
    additionalInputs - Additional inputs that may be needed for different operations
  Returns:
    RiskAssessment - Contains RiskAdvice, a new DeviceId which should be placed on the user machine, a RiskScore and other transaction related information.
  Throws:
    RiskException - If request fails for any reason.
  */

  // Sample code to evaluate risk associated with the transaction.

  RiskAssessment riskAssessment = null;
  System.out.println("The following information is used to assess the risk associated with the transaction.");

  // Build the context to be used for risk evaluation
  String callerId = "MyApplicationTrackingId"; // string used by the calling application for tracking across calls.

  // input user related information.
  UserContext userContext = new UserContext();

  //Unique identifier for the user. For example, in case of a bank it may be user's bank account number.
  userContext.setUserId("TestUser");
  userContext.setOrg("DEFAULTORG");
  System.out.println("Username: " + userContext.getUserID());
  System.out.println("Organization Name:" + userContext.getOrg());

  // input device related information
  DeviceContext deviceContext = new DeviceContext();

  // JSON Signature comes from json.js.
  String jsonSignature = "{\"navigator\":{\"platform\":\"Win32\",\"appName\":\"Netscape\",\"appCodeName\":\"Mozilla\",\"appVersion\":\"5.0 (Windows; en-US)\",\"language\":\"en-US\",\"oscpu\":\"Windows NT 5.0\",\"vendor\":\"\",\"vendorSub\":\"\",\"product\":\"Gecko\",\"productSub\":\"20070312\",\"securityPolicy\":\"\",\"userAgent\":\"Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11\",\"cookieEnabled\":true,\"onLine\":true},\"plugins\":[{\"name\":\"Adobe Acrobat Plugin\",\"version\":\"7.00\"},{\"name\":\"Macromedia Director\",\"version\":\"10.1\"},{\"name\":\"Windows Media Player Plug-in Dynamic Link Library\",\"version\":\"\"},{\"name\":\"Macromedia Shockwave Flash\",\"version\":\"9.0\"},{\"name\":\"Java Virtual Machine\",\"version\":\"1.6.0\"}],\"screen\":{\"availHeight\":690,\"availWidth\":1024,\"colorDepth\":32,\"height\":768,\"pixelDepth\":32,\"width\":1024},\"extra\":{\"javascript_ver\":\"1.6\",\"timezone\":-330}}";
 
  deviceContext.buildDeviceSignature(jsonSignature, null, null);
  System.out.println("Device Signature: " + deviceContext.getDeviceSignature());

  // Set the device id
  String idType = "HTTP_COOKIE";
  /* During the first call to evaluateRisk, deviceId=null as the device is not recognized by RiskFort server.
   * RiskFort server then sets a deviceId in a cookie on the user's machine which is passed to RiskFort server during subsequent transactions.
  */
  String deviceId = null;
  deviceContext.setDeviceID(idType, deviceId);

  /* For each transaction, either the deviceId or the aggregatorID but not both should to be set.

deviceContext.setAggregatorID("LcPywTghrtyed6KDuRcMbWiFFTYR2oFThfdDOtBKqKcdEXsH9dFIFfrr/dsfdud");

    System.out.println("Aggregator ID: " + deviceContext.getAggregatorID());
  */

  // input location related information.
  LocationContext locationContext = new LocationContext();

  InetAddress ipAddress = null;
  // IP address of the user's machine, typically extracted from the HTTP header.
  try {
      ipAddress = InetAddress.getByName("127.0.0.1");
  } catch (UnknownHostException e) {
      // Take suitable action.
  }

  locationContext.setIpAddress(ipAddress);
  System.out.println("Ip address: " + locationContext.getIPAddress());

  // input transaction related information.
  TransactionContext transactionContext = new TransactionContext();

  transactionContext.setAction("action");
  transactionContext.setChannel("DEFAULT");

  /*For each transaction, either the extensible elements must be set in the transaction context or the additional inputs must be set.

transactionContext.setExtensibleElements("MerchantID=id;MerchantCountry=country;MerchantName=name");
  */

  HashMap<String,String> additionalInputs = new HashMap<String,String>();

  String extName1 = "MerchantID";
  String extValue1 = "id";
  String extName2 = "MerchantCountry";
  String extValue2 = "country";
  String extName3 = "MerchantName";
  String extValue3 = "name";
  //Below attributes has to be supplied when organization is configured for using accounts.(not required otherwise)
  //In this case, USERID attribute inside userContext will be treated as account so below information is required
  // to identify the actual use to which this account belongs.
  String extName4 = "ACCOUNTTYPE";
  String extValue4 = "accType";
  String extName5 = "PARENTUSERID"; //If organization is configured for using accounts and implicit user creation is enabled.
  String extValue5 = "parentid";
  if(extName1 != null && extName1 != "" )
    additionalInputs.put(extName1, extValue1);
  if(extName2 != null && extName2 != "" )
    additionalInputs.put(extName2, extValue2);
  if(extName3 != null && extName3 != "" )
    additionalInputs.put(extName3, extValue3);
  if(extName4 != null && extName4 != "" )
    additionalInputs.put(extName4, extValue4);
  if(extName5 != null && extName5 != "" )
    additionalInputs.put(extName5, extValue5);
  try {
    System.out.println("evaluateRisk called.");
    // Call the API to evaluate the risk associated with the transaction.
    riskAssessment  = api.evaluateRisk(callerId, deviceContext, locationContext, userContext, transactionContext /*, additionalInputs */);

    System.out.println("evaluateRisk succeeded.");
    System.out.println("Device Id set on the user's machine: " + riskAssessment.getOutputDeviceId());
  } catch (RFSDKException e) {
    /* The following methods on UserRepositoryException object can be used to get the error codes and error messages as follows:
    * String code = e.getErrorCode();
    * String message = e.getMessage();
    */
    System.out.println("Exception in 'evaluateRisk'.");
    /*System.out.println("Error code: " + e.getErrorCode());*/
    System.out.println("Error message: " + e.getMessage());

    /* The following error codes are returned by the API. */

    /* ERRCODE_INVALID_PACKET_FROM_SERVER
    * Possible Reason:
    *   Invalid Packet type received from the server.
    * Possible Action:
    *   Report transaction failure and ask for a retry.
    */

    /* ERRCODE_PARSING_DATA
    * Possible Reason:
    *   Error in parsing the xml from the server.
    * Possible Action:
    *   Report transaction failure and ask for a retry.
    */
  }
  catch (RiskException e) {
    /* The following methods on UserRepositoryException object can be used to get the error codes and error messages as follows:
    * String code = e.getErrorCode();
    * String message = e.getMessage();
    */
    System.out.println("Exception in 'evaluateRisk'.");
    /*System.out.println("Error code: " + e.getErrorCode());*/
    System.out.println("Error message: " + e.getMessage());

    /* The following error codes are returned by the API. */

    /* ERRCODE_INVALID_PACKET_FROM_SERVER
    * Possible Reason:
    *   Invalid Packet type received from the server.
    * Possible Action:
    *   Report transaction failure and ask for a retry.
    */

    /* ERRCODE_PARSING_DATA
    * Possible Reason:
    *   Error in parsing the xml from the server.
    * Possible Action:
    *   Report transaction failure and ask for a retry.
    */
   
  }


  /*
  postEvaluate:
    Helps to make the final decision on the transaction based on the output of evaluateRisk and any second authentication that may have been performed by the calling application.
    Also takes care of updating information in the RiskFort system as needed.

  public PostEvaluateResponse postEvaluate(java.lang.String callerId,
       RiskAssessment riskAssessment,
       boolean secondaryAuthenticationStatus,
       java.lang.String associationName,
       AdditionalInputs additionalInputs)
       throws RiskException;


  Parameters:
    callerId - An identifier as decided by the application calling the API for it's own tracking.
    riskAssessment - The output from evaluateRisk.
    secondaryAuthenticationStatus - Result of second authentication.
        Pass "true" if secondary authentication succeeded, "false" otherwise.
        If evaluateRisk returned an advice other than INCREASEAUTH (i.e. secondary authentication was not asked for), pass "false".

    associationName - A value that user chose as the association name for the machine from where the transaction has been carried out.
        User should be recommended not to choose association for shared machines, in which case "null" can be passed.
    additionalInputs - Additional inputs that may be needed for different operations. This has been kept for future use.
  Returns:
    PostEvaluateResponse - Indicates whether or not this transaction should be allowed to continue. Can be checked using isAllowAdvised() which returns "true" if the transaction should be allowed and "false" if it should be denied.

  Throws:
    RiskException - If request fails for any reason.
  */

  // Sample code to make the final decision on the transaction based on the output of evaluateRisk and any second authentication that may have been performed by the calling application.
  // Here the RiskAssessment object passed as input is the object returned by the call to evaluateRisk()

  PostEvaluateResponse postEvalResponse = null;

  String associationName; // the association name for the machine from where the transaction has been carried out

  boolean secondaryAuthenticationStatus; // Result of any second authentication that may have been performed by the calling application.

  // Build the context to be used in the postEvaluate call.
  associationName = "testAssociationName";
  secondaryAuthenticationStatus = true;
 
 /*  Map */ additionalInputs = new HashMap<String,String>();
 
    //Below attributes has to be supplied when organization is configured for using accounts.(not required otherwise)
    //In this case, USERID attribute inside userContext will be treated as account so below information is required
    // to identify the actual use to which this account belongs. This has to be supplied in postEvaluate as well.
    /*String */ extName1 = "ACCOUNTTYPE";
    /*String */ extValue1 = "accType";
    /*String */ extName2 = "PARENTUSERID"; //If organization is configured for using accounts and implicit user creation is enabled.
    /*String */ extValue2 = "parentid";
    if(extName1 != null && extName1 != "" )
      additionalInputs.put(extName1, extValue1);
    if(extName2 != null && extName2 != "" )
      additionalInputs.put(extName2, extValue2);
   
  try {
    System.out.println("Calling postEvaluate with Secondary Authentication Status = " + secondaryAuthenticationStatus );
    System.out.println("Association name passed: " + associationName);

    // Call the API to make the final decision based on evaluateRisk and second Authentication.
    postEvalResponse = api.postEvaluate(callerId, riskAssessment, secondaryAuthenticationStatus, associationName /*, additionalInputs*/ );

    System.out.println("postEvaluate succeeded.");
  } catch (RFSDKException e) {

    /* The following methods on UserRepositoryException object can be used to get the error codes and error messages as follows:
    * String code = e.getErrorCode();
    * String message = e.getMessage();
    */
    System.out.println("Exception in 'postEvaluate'.");
    /* System.out.println("Error code: " + e.getErrorCode()); */
    System.out.println("Error message: " + e.getMessage());

    /* The following error codes are returned by the API. */

    /* ERRCODE_INVALID_PACKET_FROM_SERVER
    * Possible Reason:
    *    Invalid Packet type received from the server.
    * Possible Action:
    *    Report transaction failure and ask for a retry.
    */

    /* ERRCODE_PARSING_DATA
    * Possible Reason:
    *    Error in parsing the xml from the server.
    * Possible Action:
    *    Report transaction failure and ask for a retry.
    */
  }
  catch (RiskException e) {

    /* The following methods on UserRepositoryException object can be used to get the error codes and error messages as follows:
    * String code = e.getErrorCode();
    * String message = e.getMessage();
    */
    System.out.println("Exception in 'postEvaluate'.");
    /* System.out.println("Error code: " + e.getErrorCode()); */
    System.out.println("Error message: " + e.getMessage());

    /* The following error codes are returned by the API. */

    /* ERRCODE_INVALID_PACKET_FROM_SERVER
    * Possible Reason:
    *    Invalid Packet type received from the server.
    * Possible Action:
    *    Report transaction failure and ask for a retry.
    */

    /* ERRCODE_PARSING_DATA
    * Possible Reason:
    *    Error in parsing the xml from the server.
    * Possible Action:
    *    Report transaction failure and ask for a retry.
    */
  }
  System.out.println("Risk Evaluation done.");
  }
}

To Compile on Microsoft Windows

To compile this test program, save it in a file called Assess_Risk.java. Make sure that the arcot-riskfort-evaluaterisk.jar and related jar files arcot_core.jar, arcot-riskfort-mfp.jar, bcprov-jdk14-131.jar, commons-lang-2.0.jar, commons-pool-1.4.jar are in the JAVA compiler’s CLASSPATH. Then run the JAVA compiler.

The arcot-riskfort-evaluaterisk.jar file is usually present in the sdk\java\lib\arcot directory in the RiskMinder installation directory. If your Assess_Risk.java file is saved in \Program Files\Arcot Systems\sdk\java, then use the following command shown below. If your JAVA file is not in this directory, provide the full pathname to the sdk\java\lib directory in CLASSPATH.

> cd \program files\arcot systems\sdk\java

> javac -classpath ".;lib\arcot\arcot-riskfort-evaluaterisk.jar;lib\arcot\arcot_core.jar;lib\arcot\arcot-riskfort-mfp.jar;lib\external\bcprov-jdk14-131.jar;lib\external\commons-lang-2.0.jar;lib\external\commons-pool-1.4.jar;%CLASSPATH%" Assess_Risk.java

This creates the output file Assess_Risk.class in the same directory as the JAVA file.

To Compile on UNIX-Based Platforms

To compile this test program, save it in a file called Assess_Risk.java. Make sure that the arcot-riskfort-evaluaterisk.jar and related jar files arcot_core.jar, arcot-riskfort-mfp.jar, bcprov-jdk14-131.jar, commons-lang-2.0.jar, commons-pool-1.4.jar are in the JAVA compiler’s CLASSPATH. Then run the JAVA compiler.

The arcot-riskfort-evaluaterisk.jar file is usually present in the sdk/java/lib/arcot directory in the RiskMinder installation directory. If your Assess_Risk.java file is saved in /opt/arcot/sdk/java, use the following command shown below. If your JAVA file is not in this directory, provide the full pathname to the sdk/java/lib directory in CLASSPATH.

> cd /opt/arcot/sdk/java

> javac -classpath ".:./lib/arcot/arcot-riskfort-evaluaterisk.jar:./lib/arcot/arcot_core.jar:./lib/arcot/arcot-riskfort-mfp.jar:./lib/external/bcprov-jdk14-131.jar:./lib/external/commons-lang-2.0.jar:./lib/external/commons-pool-1.4.jar:$CLASSPATH" Assess_Risk.java

This creates output file Assess_Risk.class in the same directory as the JAVA file.

To Run on Microsoft Windows

Before you can run the test, the RiskMinder Service must be installed and started. To run the test, make sure that the SDK library is in the path and arcot-riskfort-evaluaterisk.jar is in the CLASSPATH then run the JAVA command as shown below.

To run the test, use the following commands:

> cd \program files\arcot systems\sdk\java

> java -classpath ".;lib\arcot\arcot-riskfort-evaluaterisk.jar;lib\arcot\arcot_core.jar;lib\arcot\arcot-riskfort-mfp.jar;lib\external\bcprov-jdk14-131.jarlib\external\commons-lang-2.0.jarlib\external\commons-pool-1.4.jar;%CLASSPATH%" Assess_Risk

To Run on UNIX-Based Platforms

Before you can run the test, the RiskMinder Service must be installed and started. To run the test, make sure that the SDK library is in the path and arcot-riskfort-evaluaterisk.jar is in the CLASSPATH then run the JAVA command as shown below.

To run the test, use the following commands:

> cd /opt/arcot/sdk/java

> java -classpath ".:./lib/arcot/arcot-riskfort-evaluaterisk.jar:./lib/arcot/arcot_core.jar:./lib/arcot/arcot-riskfort-mfp.jar:./lib/external/bcprov-jdk14-131.jar:./lib/external/commons-lang-2.0.jar:./lib/external/commons-pool-1.4.jar:$CLASSPATH" Assess_Risk

Expected Output

After running the provided sample code, you should see the following output:

Initializing RiskFort API using /riskfort.risk-evaluation.properties
RiskFort API initialized.
The following information is used to assess the risk associated with the transaction.
Username: TestUser
Organization Name:DEFAULTORG
Device Signature: {"navigator":{"platform":"Win32","appName":"Netscape","appCodeName":"Mozilla","appVersion":"5.0 (Windows; en-US)","language":"en-US","oscpu":"Windows NT 5.0","vendor":"","vendorSub":"","product":"Gecko","productSub":"20070312","securityPolicy":"","userAgent":"Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11","cookieEnabled":true,"onLine":true},"plugins":[{"name":"Adobe Acrobat Plugin","version":"7.00"},{"name":"Macromedia Director","version":"10.1"},{"name":"Windows Media Player Plug-in Dynamic Link Library","version":""},{"name":"Macromedia Shockwave Flash","version":"9.0"},{"name":"Java Virtual Machine","version":"1.6.0"}],"screen":{"availHeight":690,"availWidth":1024,"colorDepth":32,"height":768,"pixelDepth":32,"width":1024},"extra":{"javascript_ver":"1.6","timezone":-330}}
Ip address: /127.0.0.1
evaluateRisk called.
evaluateRisk succeeded.
Device Id set on the user's machine: qcd+Vq3NC6qAafCDbsFCBrup0y+z+ci8qjV5QmZI9GWuFGbbX9oIgw==
Calling postEvaluate with Secondary Authentication Status = true
Association name passed: testAssociationName
postEvaluate succeeded.
Risk Evaluation done.