Business Logic

 

+
Search Tips   |   Advanced Search

 

Business logic is any Java code that is invoked as an action when an event occurs, such as...

Business logic can be added through coding or through *.jar files.

Because business logic is basically code, the number of things you can use business logic for are, technically, infinite. Among the more mundane usages are...

If you add business logic to your HATS application, modify the WAR classloader policy of your HATS application on WAS when you deploy your HATS application and on the local server in HATS Studio if you use Run on Server to test your business logic.

You can create business logic and add it to your project using the Create Business Logic wizard. To invoke this wizard, right-click in the HATS Project View tab of the HATS Studio, and select...

New HATS | Business Logic

In the Create Business Logic wizard, specify the project to which you want to add the business logic and supply the Java class name. Optionally, you can supply a package name, or select an existing Java package by clicking Browse. If you want your business logic to include stub methods for easy access to the project global variables, check the Get global variable and Set global variable check box. Click Finish when you have provided the required information.

After you create your business logic class, you will want to link it to one or more screen customizations or application events so that it is executed when that event occurs. Edit each event (application event or screen customization) to which you want to add it. On the Actions panel, click Add, then fill in the details for your business logic class. Refer to HATS User's and Administrator's Guide for information about editing screen customizations and events.

You can see the business logic files in the project by expanding the Source folder on the HATS Project View tab of the HATS Studio. Each package name or class name appears in the Source folder. Expand the package name folder to see the Java class name. Double-click on the class name to edit the class. The Source folder can also include other Java files that have been imported into your HATS project.

If you use the Create Business Logic wizard to create business logic, the method that will be invoked by the execute action is named "execute" by default. If you write your own class, the method must meet specific requirements. It must:

The method must follow the form:

public static void myMethod (BusinessLogicInfo businesslogic)

followed by your own business logic code.

The BusinessLogicInfo object passed to your custom Java code enables you to access and use or modify various objects and settings of your HATS project. These include:

For more information about the classes made available to you, see the HATS API documentation at the HATS Web infocenter (http://www.ibm.com/software/webservers/hats/library/version5/infocenter/) for the BusinessLogicInfo class.

 

Incorporating Java code from other applications

You can incorporate Java code from other existing applications into your HATS projects in a variety of ways.

If you want to incorporate the source code (.java files) from your existing business logic so you can modify the code, you can import the .java files into the Source folder in your existing project. Select File > Import > File System to open the Import wizard. In the Import wizard, select the location of your source files in the From directory: field. Select the Source folder of your project in the destination Into folder: entry field. When your source .java files are imported, they are automatically compiled and packaged into your HATS project. You can also edit, set breakpoints, and debug your source files in the WebSphere Studio workbench.

You can also incorporate a Java archive (.jar) file with compiled Java business logic. This approach imports the Java archive file into the .ear project. The entire Java archive is added; you cannot select individual classes to add. There will only be a single copy of the .jar file in the .ear file, but it is available to all of the HATS projects contained in that .ear project. There are three steps to this method.

  1. Import the .jar file into the HATS .ear project. Select File > Import > File System to open the Import wizard. Select the Java archive (.jar) you want to import in the From directory: field. Select your HATS .ear project as the destination in the Into folder: field. When your .jar file is imported, click the Navigator tab of the HATS Studio and expand your HATS ear project. You will see the imported java archive file.
  2. In the Navigator tab of the HATS Studio, select the project in which you want to invoke your business logic. Right-click on the high level HATS project and select Properties. In the Properties dialog, select Java Build Path in the left table and select the Libraries tab on the right. Click Add JARs to display the JAR Selection dialog. Expand the HATS .ear project, and select the newly imported Java archive file. Click OK in the JAR Selection dialog, and click OK in the Properties dialog. Repeat this process for all HATS projects for which you want to use the business logic.
  3. In the Navigator tab of the HATS Studio, again select the project in which you want to invoke your business logic. Expand the project, the Web Content folder, and the META-INF folder. Double-click the MANIFEST.MF file to open the JAR dependencies editor. Check the box next to each .jar file that you want to include in your project's classpath.

There are other ways to import Java archives into the HATS project. HATS projects are extensions of Web projects in the WebSphere Studio workbench. For more information about importing files into Web projects, open the WebSphere Studio Help and search for Web projects.

 

Use global variables in business logic

If your HATS application uses global variables to store information, you can use these global variables in your business logic. When you create your business logic class, use the Create business logic wizard and check the Get global variable checkbox. This will create a stub that makes it easy to read and set global variables.

Here is the stub that is created:

 /**
   * Example method that sets a named global variable 
 * from the current session to a value
   * @param blInfo - BusinessLogicInfo from current session
   * @param name - Name of the global variable
   * @param value - Value of the global variable
   */
public static void setGlobalVariable(BusinessLogicInfo blInfo,
     String name,Object value)
{
  IGlobalVariable gv = blInfo.getGlobalVariable(name);
  if ( gv == null )
  {
    gv = new GlobalVariable(name,value);
  }
  else
  {
    gv.set(value); 
  }
  blInfo.getGlobalVariables().put(name,gv);
}

/**
 * Example method that sets a named shared
 * global variable from the current session to a value
 * @param blInfo - BusinessLogicInfo from current session
 * @param name - Name of the shared global variable
 * @param value - Value of the shared global variable
 */ 
public static void setSharedGlobalVariable(BusinessLogicInfo 
   blInfo,String name,Object value)
{
  IGlobalVariable gv = blInfo.getSharedGlobalVariable(name);
  if ( gv == null )
  {
    gv = new GlobalVariable(name,value);
  }
  else
  {
    gv.set(value); 
  }
  blInfo.getSharedGlobalVariables().put(name,gv);
}

/**
 * Example method that retrieves a named global variable from the current session
 * @param blInfo - BusinessLogicInfo from current session
 * @param name - Name of the global variable
 */
public static IGlobalVariable getGlobalVariable(BusinessLogicInfo 
   blInfo,String name)
{ 
  IGlobalVariable gv = blInfo.getGlobalVariable(name);
  return gv;
}

/**
 * Example method that retrieves a named shared 
 * global variable from the current session
 * @param blInfo - BusinessLogicInfo from current session
 * @param name - Name of the shared global variable
 */
public static IGlobalVariable getSharedGlobalVariable(BusinessLogicInfo 
   blInfo,String name)
{ 
  IGlobalVariable gv = blInfo.getSharedGlobalVariable(name);
  return gv;
}

Elsewhere in your code, when you need the value of a global variable, you can call this method:

  GlobalVariable gv1 = getGlobalVariable(blInfo,"varname");

If the global variable is indexed, use square brackets:

  GlobalVariable gv1[] = getGlobalVariable(blInfo,"varname");

There are two lists of HATS global variables, one for local variables and one for shared global variables. To get the value of a shared global variable, use this method:

  GlobalVariable gv1 = getSharedGlobalVariable(blInfo,"varname");

 

Business logic examples

This section contains examples of using business logic. Each works with global variables. Each example uses one or more of the stubs described above, and the classes should include those stubs. They are omitted in these examples to make it easier to view the example code.

 

Example: date conversion

This example converts a date from mm/dd/yy format to Monthname date, year format. For example, it converts 6/12/2004 into June 12, 2004. It assumes that the global variable theDate has been set before the business logic is called. Note how it uses this method to obtain the value of the input variable:

IGlobalVariable inputDate = getGlobalVariable(blInfo, "theDate");

After using standard Java functions to manipulate the string to represent the date in the desired format, it uses this method to put the new string into the same global variable:

setGlobalVariable(blInfo, "theDate", formattedDate);

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.ibm.hats.common.BusinessLogicInfo;
import com.ibm.hats.common.GlobalVariable;
import com.ibm.hats.common.IGlobalVariable;

public class CustomDateFormatter
{

       public static void execute(BusinessLogicInfo blInfo)
      {
       IGlobalVariable inputDate = getGlobalVariable(blInfo, "theDate");
         SimpleDateFormat inputFormat = new SimpleDateFormat("MM/dd/yyyy");
          SimpleDateFormat outputFormat = new SimpleDateFormat("MMMM dd, yyyy");
        
         try {
        Date tempDate = inputFormat.parse(inputDate.getString().trim()); 
        String formattedDate = outputFormat.format(tempDate); 
        setGlobalVariable(blInfo, "theDate", formattedDate);
            } catch (ParseException ex) {
             ex.printStackTrace();
             }
     }
}

 

Example: adding the values contained in an indexed global variable

This example adds the values contained in an indexed global variable and stores the sum in another, non-indexed global variable. It assumes that you have stored strings representing numbers in the indexed global variable subtotals.

The previous example included the names of the input and output global variables ("theDate") on the set calls. This example sets the names of the input and output variables into local string variables and uses those string on the calls to get and set the global variable values. Since the name of the global variable is being passed as a variable, it is not put into quotes:

setGlobalVariable(blInfo,gvOutputName, new Float(myTotal));

import com.ibm.hats.common.BusinessLogicInfo;
import com.ibm.hats.common.GlobalVariable;
import com.ibm.hats.common.IGlobalVariable;

  public static void execute(BusinessLogicInfo blInfo)
    {
     // Name of indexed global variable to be read in
        String gvInputName = "subtotals";
        // Name of global variable to be calculated and saved
        String gvOutputName = "total";
        
        // The indexed global variabl where each index is a subtotal to be summed
        GlobalVariable gvSubtotals = 
     ((GlobalVariable)getGlobalVariable(blInfo, gvInputName));
        
        float myTotal = 0;
        
        // Calculate the total by adding all subtotals
        for (int i = 0; i < gvSubtotals.size(); i++)
        {
         myTotal = myTotal + Float.valueOf(gvSubtotals.getString(i)).floatValue();
        }
  
        // Save the total as a non-indexed local variable
        setGlobalVariable(blInfo,gvOutputName, new Float(myTotal));
    }

 

Example: reading a list of strings from a file into an indexed global variable

This example reads a file from the file system and stores the strings in the file into an indexed global variable. You could use a technique like this to read a file containing, for example, a list of your company's locations. After storing the strings in a global variable, you could use the global variable to populate a drop-down list or other widget to enable users to choose from a list of values. You could create a global rule to use this widget wherever an appropriate input field occurs. To make sure that the global variable is available as soon as the application is started, add the execute action for this business logic class to the Start event.

import com.ibm.ejs.container.util.ByteArray;
import com.ibm.hats.common.BusinessLogicInfo;
import com.ibm.hats.common.GlobalVariable;
import com.ibm.hats.common.IGlobalVariable;

public class ReadNamesFromFile
{

    public static void execute(BusinessLogicInfo blInfo)
    {
        // Name of indexed global variable to be saved
        String gvOutputName = "namesFromFile";
  

        // The file containing a list of information 
        // In this case, it contains names

        java.io.File myFileOfNames = new java.io.File("C:" 
                                                     + java.io.File.separator
                                                     + "temp" 
                                                     + java.io.File.separator 
                                                     + "names.txt");
      
     try
     {
         // First, read the contents of the file
         java.io.FileInputStream fis = new java.io.FileInputStream(myFileOfNames);
   
         int buffersize = (int)myFileOfNames.length(); 
         byte[] contents = new byte[buffersize];; 

         long n = fis.read(contents, 0, buffersize);
    
         fis.close();
   
         String namesFromFile = new String(contents);
   
         // Next, create an indexed global variable from the file contents
   
         java.util.StringTokenizer stok = 
            new java.util.StringTokenizer(namesFromFile, "\n", false);
   
         int count = stok.countTokens();
         String[] names = new String[count];

         for (int i = 0; i < count; i++)
         {
          names[i] = stok.nextToken();
         }
   
         IGlobalVariable gv = new GlobalVariable(gvOutputName, names);
         blInfo.getGlobalVariables().put(gvOutputName,gv);   
     }

     catch (java.io.FileNotFoundException fnfe)
     {
         fnfe.printStackTrace();
     }

     catch (java.io.IOException ioe)
     {
         ioe.printStackTrace();
     }

    }

 

Example: calling an Integration Object

This example illustrates calling an Integration Object from business logic. It assumes that you have an Integration Object named Iomac, which takes one input parameter, a string called input, and returns a string named output.

This business logic follows these steps:

  1. Instantiates the Integration Object:
     IntegrationObject.Iomac io = new IntegrationObject.Iomac();
  2. Sets the input variable from a global variable:
    io.setInput(getGlobalVariable(blInfo,"input").getString());
  3. Invokes the Integration Object:
    io.doHPTransaction(blInfo.getRequest(), blInfo.getResponse());
  4. Checks for exceptions.
  5. If the Integration Object executed successfully, sets the global variable output to the value returned by the Integration Object's getOutput() method:
    if (io.getHPubErrorOccurred() == 0) {
       setGlobalVariable(blInfo,"output",io.getOutput());
    

If you want to invoke an Integration Object that accepts more input variables or returns more variables, add setter and getter calls to set the input variables before invoking the Integration Object and retrieve the output values after it executes.

import com.ibm.hats.common.BusinessLogicInfo;
import com.ibm.hats.common.GlobalVariable;
import com.ibm.hats.common.IGlobalVariable;

public class myLogic
{

    public static void execute(BusinessLogicInfo blInfo)
    {
        //add code here to perform your business logic
        IntegrationObject.Iomac io = new IntegrationObject.Iomac();

  // Set Integration Object's HAOVariable "input" 
  // equal to text from HATS gv "input"
  io.setInput(getGlobalVariable(blInfo,"input").getString());
 
  // run hp transaction
  
  try {
   io.doHPTransaction(blInfo.getRequest(), blInfo.getResponse());
  }
  catch (Exception e) { 
   System.out.println("Exception thrown: " + e.toString());
   setGlobalVariable(blInfo,"output",
    "An exception was thrown. Please view the log for more details");
  }
  
  // Retrieve "output" computed through IO transaction 
  // and set it to HATS gv "output"
  
  if (io.getHPubErrorOccurred() == 0) {
   setGlobalVariable(blInfo,"output",io.getOutput());
   System.out.println("Transaction has been completed successfully.");   
  }
  else {
   setGlobalVariable(blInfo,"output","Transaction has failed unexpectedly. 
     HATS Error message = " + io.getHPubErrorMessage());
   System.out.println("Transaction failed unexpectedly. HATS Error message =
     " + io.getHPubErrorMessage()");  }
    }
}

 

Use custom screen recognition

HATS Studio provides many options for recognizing screens within a screen customization, including the number of fields on a screen, the presence or absence of strings, and the use of global variables. These options are described in HATS User's and Administrator's Guide. You might find, however, that you want to recognize a screen in a way that you cannot configure using the options in the screen customization editor. In that case you can add your own custom screen recognition logic.

The information in this section can be used for screen recognition within macros as well as within screen customizations.

If you want to create custom screen recognition logic using HATS global variables, see Custom screen recognition using global variables.

If you have already created custom screen recognition logic by extending the ECLCustomRecoListener class, you can use this logic within HATS. If you are creating new custom logic, follow these steps:

  1. Open the Java perspective.
  2. Click File > New Class.
  3. Browse to the Source directory of your HATS project.
  4. Enter the names of your package and class.
  5. For the superclass, click Browse and locate com.ibm.hats.common.customlogic.AbstractCustomScreenRecoListener.
  6. Click the check box for Inherit abstract method. Click Finish. This will import the code skeleton into the project you specified.
  7. Add your logic to the isRecognized method . Make sure that it returns a boolean value.

    public abstract boolean isRecognized(String settings, BusinessLogicInfo bli, ECLPS ps, ECLScreenDesc screenDescription)

    Please refer to the HATS API documentation at the HATS Web infocenter for a description of this method.

  8. After creating your method, update the screen recognition to invoke your method. From the HATS Project View, expand your project and the Screen Customizations folder. Double-click the name of the screen customization to which you want to add your custom logic. Click the Source tab to open the source view of the screen customization.
  9. Within the source view you will see a block that begins and ends with the <description> and </description> tags. This block contains the information used to recognize screens. Add a line within this block to invoke your custom logic:

    <customreco id="customer.class.package.MyReco::settings" invertmatch="false" optional="false"/>

    where customer.class.package.MyReco is your package and class name. If you want to pass any settings into your class, add them after the class name, separated by two colons. Settings are optional, and your class must parse whatever values are passed in. If you do not need settings, omit the two colons.

    Consider where within the description block you want to place the customreco tag. If you want your custom logic invoked only if all the other criteria match, place the customreco tag at the end of the block, immediately before the </description> tag. If your screen customization compares a screen region to a value, the description block will contain a smaller block, beginning and ending with the <block> and </block> tags, to define the value to which the screen region is compared. Be sure not to place your customreco tag inside this block.

    Here is an example section of a description block. Note the customreco tag just before the </description> tag, and not between the <block and </block> tags.

    <description>
    <oia invertmatch="false" optional="false" status="NOTINHIBITED"/>
    <numfields invertmatch="false" number="61" optional="false"/>
    <numinputfields invertmatch="false" number="16" optional="false"/>
    <block casesense="false" col="2" ecol="14" erow="21" 
       invertmatch="false" optional="false" row="20">
    <string value="USERID ==="/>
    <string value="PASSWORD ==="/>
    </block>
    <cursor col="16" invertmatch="false" optional="false" row="20"/>
    <customreco id="customer.class.package.MyReco::settings" 
       invertmatch="false" optional="false"/>
    </description>
    
    
  10. Rebuild your HATS project: in the HATS Project View: right click the name of your project and select Rebuild HATS Project.
  11. Use the Run on Server to test your project. If you receive a ClassNotFoundException error, modify the classloader policy on your server. Refer to HATS Getting Started for more information.

 

Example of custom screen recognition

Here is an example of business logic that performs custom screen recognition. This business logic class takes a list of code page numbers, separated by blanks, as its settings, and recognizes the screen if its code page matches one of those listed in the settings. The tag syntax is:

<customreco id="company.project.customlogic.CodePageValidate::[settings]" optional="false" invertmatch="false" />.

For example, you could insert this tag into a description block:

<customreco id="company.project.customlogic.CodePageValidate::037 434 1138" optional="false" invertmatch="false" />.

In this case the screen will be recognized if its code page is 037, 434, or 1138.

package company.project.customlogic;

import java.util.StringTokenizer;
import java.lang.Integer;
import com.ibm.eNetwork.ECL.ECLPS;
import com.ibm.eNetwork.ECL.ECLScreenDesc;
import com.ibm.hats.common.BusinessLogicInfo;
import com.ibm.hats.common.HostScreen;
import com.ibm.hats.common.customlogic.AbstractCustomScreenRecoListener;

public class CodePageValidate extends AbstractCustomScreenRecoListener {

/**
 * @see com.ibm.hats.common.customlogic.AbstractCustomScreenRecoListener
 * #isRecognized(java.lang.String, com.ibm.hats.common.BusinessLogicInfo,
 *       com.ibm.eNetwork.ECL.ECLPS,  com.ibm.eNetwork.ECL.ECLScreenDesc)
  */
 public boolean isRecognized(
  String settings,
  BusinessLogicInfo bli,
  ECLPS ps,
  ECLScreenDesc screenDescription) {
  HostScreen hs=bli.getHostScreen();
  int int_codepage=hs.GetCodePage();
  if(settings!=null)
  {
   StringTokenizer tokenizer = new StringTokenizer(settings);
   while( tokenizer.hasMoreTokens() )
   {   
    int int_token= Integer.valueOf(tokenizer.nextToken()).intValue();
    if ( int_token==int_codepage )
    {    
      return true;
    }
   }
  }
  return false;
 }

}

 

Custom screen recognition using global variables

HATS Studio provides some screen recognition options using global variables, including these functions:

Refer to HATS User's and Administrator's Guide for information about these options. If you want to perform screen recognition based on HATS global variables, and the options in the Global Variable Logic panel do not meet your requirements, you can add your own logic based on the values or existence of one or more global variables. This approach does not require you to create a Java class; instead, it uses the GlobalVariableScreenReco class, which is provided by HATS, and you can specify comparisons to be made as settings on the on the customreco tag. The format is:

<customreco id="com.ibm.hats.common.customlogic.GlobalVariableScreenReco::
  {variable(name,option,resource, index)}COMPARE{type(name,option,resource,index)}" 
  invertmatch="false" optional="false"/>

or

<customreco id="com.ibm.hats.common.customlogic.GlobalVariableScreenReco::
  {variable(name,option,resource, index)}COMPARE{type(value)}" 
  invertmatch="false" optional="false"/>

Note the use of {} brackets to contain each of the two items that are being compared. The first item is a HATS global variable, whose name is specified in name. Use option to specify that you want to use the variable's value, length, or existence in your comparison. The resource and index settings are optional. Use resource to indicate whether the global variable is local (which is the default) or shared. Use index to indicate which value to use from an indexed global variable.

The second item can be either

. The valid values for type are variable, integer, boolean and string. The valid values for COMPARE are EQUAL, NOTEQUAL, GREATERTHAN, GREATERTHANOREQUAL, LESS THAN, and LESSTHANOREQUAL. All the values except EQUAL and NOTEQUAL are valid only for comparing integers.

Table 1. Valid values for settings
Set Valid values
type

  • variable
  • integer
  • boolean
  • string

COMPARE

  • EQUAL
  • NOTEQUAL
  • GREATERTHAN
  • GREATERTHANOREQUAL
  • LESS THAN
  • LESSTHANOREQUAL

options

  • exists (boolean)
  • value (string/integer/boolean)
  • length (integer)
  • object (object)

resource

  • local
  • shared

index any positive integer or zero

Let's look at some examples. In the first example we'll compare the values of two local global variables:

<customreco id="com.ibm.hats.common.customlogic.GlobalVariableScreenReco::
  {variable(name=gv1,option=value,resource=local)}EQUAL
  {variable(name=gv2,option=value,resource=local)}" 
  invertmatch="false" optional="false"/>

This expression will evaluate to true if the values of gv1 and gv2 are the same.

Now let's look at the length option. For a non-indexed global variable, length will be the length of the value of the variable. For an indexed global variable, if you specify an index, length will be the length of that index of the global variable; if you do not specify an index, length will be the number of indexed entries in the global variable.

<customreco id="com.ibm.hats.common.customlogic.GlobalVariableScreenReco::
  {variable(name=gv1,option=length,resource=shared)}LESSTHANOREQUAL
  {variable(name=gv2,option=length,index=4)}" invertmatch="false" optional="false"/>

This expression compares the length of gv1 to the length of the fourth index of gv2. It will evaluate to true if the length of gv1 is less than or equal to the length of the fourth index of gv2. We can use LESSTHANOREQUAL because length returns an integer value.

Note the use of resource=shared on gv1 in this example. This indicates that gv1 is a shared global variable. The other option is resource=local, which is the default, and means that the global variable is not shared with other applications.

You do not have to compare one global variable with another. You can compare the length of a global variable with a fixed integer. You can compare the value of a global variable with another string. For example,


<customreco id="com.ibm.hats.common.customlogic.GlobalVariableScreenReco::
  {variable(name=gv1,option=value)}EQUAL{string(value=mystring)}" 
  invertmatch="false" optional="false"/>

This expression compares the value of gv1 with the string contained in mystring. The string can be a fixed string, the value of a variable, or a value returned from a method call. In general, you do not need to use custom logic to compare the length or value of a global variable to a fixed value; you can add these comparisons using the Global Variable Logic panel.

See also

  1. Integrating Jakarta Commons Logging with IBM WebSphere Application Server V5
  2. Error using Apache commons logging framework on WPS 5.0.2? StrutsLogFactory

 

Home