Integrating the Bonus entity bean with MyNewControllerCmd

In this lesson, you will integrate the Bonus entity bean with the MyNewControllerCmd logic. The MyNewJSPTemplate.jsp file uses the bean to provide updates of the total balance of bonus reward points earned by a registered user.

About this task

Procedure

  1. Create the BonusDataBean data bean that extends the BonusAccessBean to display bonus points in a JSP page. To be consistent with the programming model, you will create a new data bean that corresponds to the new Bonus entity bean. Entity beans are not required to have a corresponding data bean, however, to display information from the entity bean in a JSP page, you should create a data bean for this purpose.
    1. Navigate to WebSphereCommerceServerExtensionsLogic > src > com.ibm.commerce.sample.databeans.
    2. Open the BonusDataBean.java class to view its source code.
    3. In the source code, uncomment Section 1, to introduce the following code into the bean:
      
      /// Section 1 ///////////////////////////////////////////////
      
      // create fields and accessors (setter/getter methods) 
        
        private java.lang.String userId;
        private java.lang.Integer totalBonusPoints;
        
         
        public java.lang.String getUserId() {
          return userId;
        }
      
        public void setUserId(java.lang.String newUserId) {
          userId = newUserId;
          
          ///////////////////////////////////////
          /// Section A : instantiate BonusAccessbean
      
          if (userId != null)
            this.setInitKey_memberId(new Long(newUserId));
      
          ///////////////////////////////////////   
        }
      
      
          public java.lang.Integer getTotalBonusPoints() {
          return totalBonusPoints;
        }
        public void setTotalBonusPoints(java.lang.Integer newTotalBonusPoints) {
          totalBonusPoints= newTotalBonusPoints;
        }
      
       
      //// End of section 1 ////////////////////////////////////////////
      
    4. Next, uncomment Section 2, to introduce the following section of code into the bean:
      
      /// Section 2///////////////////////////////////////////////
      
      // create a new constructor for passing access bean into databean 
      // so that JSP can work with the access bean
      
      public BonusDataBean(BonusAccessBean bb) 
         throws com.ibm.commerce.exception.ECException {
        try {
          super.setEJBRef(bb.getEJBRef());
        }  catch (javax.ejb.FinderException e) {
              throw new ECSystemException(ECMessage._ERR_CREATE_EXCEPTION,
              "BonusDataBean", "BonusDataBean(bb)");
        } catch (javax.naming.NamingException e) {
          throw new ECSystemException(ECMessage._ERR_NAMING_EXCEPTION, 
                 "BonusDataBean", "BonusDataBean(bb)");
        } catch (java.rmi.RemoteException e) {
          throw new ECSystemException(ECMessage._ERR_REMOTE_EXCEPTION, 
                 "BonusDataBean", "BonusDataBean(bb)");
        } catch (javax.ejb.CreateException e) {
          throw new ECSystemException(ECMessage._ERR_CREATE_EXCEPTION,  
                 "BonusDataBean", "BonusDataBean(bb)");
        }
      }
      
      //// End of section 2 ////////////////////////////////////////////
      
    5. Next, uncomment Section 3, to introduce the following code into the bean:
      
      //// Section 3 /////////////////////////////////////////////////
      
      // set additional data field that is used for instantiating BonusAccessbean
      
        try
        {
        
          setUserId(getRequestProperties().getString("taskOutputUserId"));
          
          try {
            super.refreshCopyHelper();
          } catch (javax.ejb.FinderException e) {
              throw new ECSystemException(ECMessage._ERR_CREATE_EXCEPTION,
              "BonusDataBean", "populate"); 
        } catch (javax.naming.NamingException e) {
          throw new ECSystemException(ECMessage._ERR_NAMING_EXCEPTION, 
                 "BonusDataBean", "populate");
        } catch (java.rmi.RemoteException e) {
          throw new ECSystemException(ECMessage._ERR_REMOTE_EXCEPTION, 
                 "BonusDataBean", "populate");
        } catch (javax.ejb.CreateException e) {
          throw new ECSystemException(ECMessage._ERR_CREATE_EXCEPTION,  
                 "BonusDataBean", "populate");
        }
          
      
        }
        catch (ParameterNotFoundException e){}
      
      
      ///// End of Section 3 /////////////////////////////////////////
      }
      
    6. Next, uncomment Section 4 to introduce the following code into the bean:
      
      /// Section 4 ///////////////////////////////////////////
      
      // copy input TypedProperties to local
      
        requestProperties = aParam;
      
      /// End of section 4 ////////////////////////////////////
      
    7. Save your changes.
  2. Modifying the MyNewTaskCmd interface to specify the required fields and methods for bonus points
    1. Expand WebSphereCommerceServerExtensionsLogic > src > com.ibm.commerce.sample.commands
    2. Open the MyNewTaskCmd interface for editing.
    3. Uncomment Import section 2 to include the following package:
      
      /// Import section 2 /////////////////////////////////////
      import com.ibm.commerce.extension.objects.BonusAccessBean;
      /// End of import section 2 //////////////////////////////
      
    4. Uncomment Section 4 to introduce the following code into the method:
      
      /// Section 4 ////////////////////////////////////////////////
        
        public java.lang.Integer getOldBonusPoints();
        public Integer getTotalBonusPoints();
        
        public void setBonusAccessBean(BonusAccessBean bb);
        public BonusAccessBean getBonusAccessBean();
        
      
      /// End of section 4//////////////////////////////////////////
      
    5. Save the changes. Errors and warnings that might display in the task view will be resolved in a later step.
  3. To modify MyNewTaskCmdImpl to calculate bonus points: The MyNewTaskCmdImpl is used as the point of integration between the Bonus entity bean and the MyNewControllerCmd (since MyNewControllerCmd invokes the MyNewTaskCmd).
    1. Expand WebSphereCommerceServerExtensionsLogic > src > com.ibm.commerce.sample.commands
    2. Open the MyNewTaskCmdImpl class for editing
    3. Uncomment Import section 2 to introduce the following package. You might have to expand the import section to display Import section 2.
      
      /// Import section 2 //////////////////////////////////////
      import com.ibm.commerce.extension.objects.BonusAccessBean;
      ///  End of Import section 2 ///////////////////////////////
      
    4. Uncomment Sections 3A and 3B to introduce the following code into the class:
      
      //// Section 3A //////////////////////////////////////////////
      
        private java.lang.Integer oldBonusPoints;
        private java.lang.Integer totalBonusPoints;
        
        
        private BonusAccessBean bb = null;
      
      ////End of Section 3A /////////////////////////////////////////
      
      //// Section 3B //////////////////////////////////////////////  
        
        public void setBonusAccessBean(BonusAccessBean newBB) {
          bb = newBB;
        }
        
        public BonusAccessBean getBonusAccessBean(){
          return bb;
        }
        
          public java.lang.Integer getOldBonusPoints() {
          return oldBonusPoints;
        }
        
        public Integer getTotalBonusPoints(){
          return totalBonusPoints;
        }
        
      
      /// End of section 3B ///////////////////////////////////////////
      
    5. In the Outline view, select the validateParameters method and uncomment Section 2, to introduce the following code into the method:
      
      // section 2 /////////////////////////////////////////////////////
      
        try {
            oldBonusPoints = bb.getBonusPoint();
        } catch (javax.ejb.FinderException e) {
          try {
            // If bb is null, create a new instance 
              short optCounter=(short)0;
            bb = new BonusAccessBean(new Long(foundUserId), new Integer(0), optCounter);
            oldBonusPoints = new Integer(0);
          } catch (javax.ejb.CreateException ec) {
            throw new ECSystemException(ECMessage._ERR_CREATE_EXCEPTION,
              this.getClass().getName(), "validateParameters");
          } catch (javax.naming.NamingException ec) {
            throw new ECSystemException(ECMessage._ERR_NAMING_EXCEPTION,
              this.getClass().getName(), "validateParameters");
          } catch (java.rmi.RemoteException ec) {
            throw new ECSystemException(ECMessage._ERR_REMOTE_EXCEPTION,
              this.getClass().getName(), "validateParameters");
          }
        } catch (javax.naming.NamingException e) {
          throw new ECSystemException(ECMessage._ERR_NAMING_EXCEPTION,
            this.getClass().getName(), "validateParameters");
        } catch (java.rmi.RemoteException e) {
          throw new ECSystemException(ECMessage._ERR_REMOTE_EXCEPTION,
            this.getClass().getName(), "validateParameters");
        } catch (javax.ejb.CreateException e) {
          throw new ECSystemException(ECMessage._ERR_CREATE_EXCEPTION,
            this.getClass().getName(), "validateParameters");
        }
         
      // end of section 2 ///////////////////////////////////////////////
      
    6. In the Outline view, select the performExecute method.
    7. In the source code for this performExecute method, uncomment Section 2. This introduces the following code into the method:
      
      /// Section 2 ///////////////////////////////////////////////////
      
      
      /// use BonusAccessBean to update new bonus point
      
        int newBP =  oldBonusPoints.intValue() + getInputPoints().intValue();
        totalBonusPoints = new Integer (newBP);
        bb.setBonusPoint(totalBonusPoints)   ;
            
        try {
          bb.commitCopyHelper();
        } catch (javax.ejb.FinderException e) {
          throw new ECSystemException(ECMessage._ERR_FINDER_EXCEPTION,
                 this.getClass().getName(), "performExecute");
        } catch (javax.naming.NamingException e) {
          throw new ECSystemException(ECMessage._ERR_NAMING_EXCEPTION,
                 this.getClass().getName(), "performExecute");
        } catch (java.rmi.RemoteException e) {
          throw new ECSystemException(ECMessage._ERR_REMOTE_EXCEPTION,
                 this.getClass().getName(), "performExecute");
        } catch (javax.ejb.CreateException e) {
          throw new ECSystemException(ECMessage._ERR_CREATE_EXCEPTION,
                 this.getClass().getName(), "performExecute");
        }
      
      /// End of section 2 ////////////////////////////////////////////
      
      
    8. Save your changes.
  4. Adding a getResources method to the MyNewControllerCmdImpl class. In this section, you add a new getResources method to the MyNewControllerCmdImpl. This method returns a list of resources that the command uses during processing. This method is required for resource level access control.
    1. Expand WebSphereCommerceServerExtensionsLogic > src > com.ibm.commerce.sample.commands
    2. Open the MyNewControllerCmdImpl class for editing.
    3. Uncomment Section 3, to introduce the following code into the class:
      /// Section 3 ////////////////////////////////////////////////
      /// Create an instance variable of type AccessVector to hold 
      /// the resources and a BonusAccessBean instance variable for 
      /// access control purposes.
      
          private AccessVector resources = null;
          private BonusAccessBean bb = null;
      
      /// End of Section 3 /////////////////////////////////////////
      
    4. In the source code, uncomment the Access Control Section. This section displays as shown in the following code snippet:
      
      /// AccessControl Section ////////////////////////////////////
      
      public AccessVector getResources() throws ECException{
      
       if (resources == null ) {
      
          /// use UserRegistryAccessBean to check user reference number
      
        String refNum = null;
        String methodName = "getResources";
      
        rrb = new UserRegistryAccessBean();
      
        try {
          rrb = rrb.findByUserLogonId(getUserName());
          refNum = rrb.getUserId();
        } catch (javax.ejb.FinderException e) {
          throw new ECSystemException(ECMessage._ERR_FINDER_EXCEPTION,
              this.getClass().getName(),methodName,e);
        } catch (javax.naming.NamingException e) {
          throw new ECSystemException(ECMessage._ERR_NAMING_EXCEPTION,
              this.getClass().getName(), methodName,e);
        } catch (java.rmi.RemoteException e) {
          throw new ECSystemException(ECMessage._ERR_REMOTE_EXCEPTION,
              this.getClass().getName(), methodName,e);
        } catch (javax.ejb.CreateException e) {
          throw new ECSystemException(ECMessage._ERR_CREATE_EXCEPTION,
              this.getClass().getName(), methodName,e);
        }
      
      
        /// find the bonus bean for this registered user
      
          bb = new com.ibm.commerce.extension.objects.BonusAccessBean(); 
        try {
          if (refNum != null) {
            bb.setInitKey_memberId(new Long(refNum)); 
            bb.refreshCopyHelper();
            resources = new AccessVector(bb);
          }
        } catch (javax.ejb.FinderException e) {
      
       //We don't have a bonus object so return the container that will hold the 
      //bonus object when it's created
      UserAccessBean uab = new UserAccessBean();
      uab.setInitKey_MemberId(refNum);
      resources = new AccessVector(uab);
      return resources;
      
        } catch (javax.naming.NamingException e) {
          throw new ECSystemException(ECMessage._ERR_NAMING_EXCEPTION, 
              this.getClass().getName(), methodName);
        } catch (java.rmi.RemoteException e) {
          throw new ECSystemException(ECMessage._ERR_REMOTE_EXCEPTION, 
              this.getClass().getName(), methodName);
        } catch (javax.ejb.CreateException e) {
          throw new ECSystemException(ECMessage._ERR_CREATE_EXCEPTION, 
              this.getClass().getName(), methodName);
        }
      
       }
        return resources;
      }
      
      /// End of AccessControl Section //////////////////////////////////
      
    5. Save your changes.
  5. Modifying the performExecute method of the MyNewControllerCmdImpl class. In this step you will modify the code in the performExecute method of the MyNewControllerCmdImpl to include code related to the new bonus bean, as follows
    1. In the Outline view, select the performExecute method of MyNewControllerCmdImpl.
    2. In the source code, uncomment Sections 4E, 4G, and 4H to introduce the following code into the method:
      
      // Section 4E ////////////////////////////////////
      /// pass bb instance variable to the task command
          cmd.setBonusAccessBean(bb);
      // End of section 4E /////////////////////////////
      
      // Section 4G ///////////////////////////////////////
      if (cmd.getOldBonusPoints() != null) {
            rspProp.put("oldBonusPoints", cmd.getOldBonusPoints());
      }
      // End of section 4G /////////////////////////////
      
      // Section 4H ///////////////////////////////////////
      ///Instantiate the bonus data bean , then put it to response properties
         BonusDataBean bdb  = 
            new com.ibm.commerce.sample.databeans.BonusDataBean(
               cmd.getBonusAccessBean());
         rspProp.put("bdbInstance", bdb );
      // End of section 4H ////////////////////////////////
      
    3. At this point, there are compilation errors. To correct them, right-click anywhere over the Java code editor and select Source > Organize Imports.
    4. Save your changes.
  6. Creating the access control policy for the new entity bean. A sample access control policy is provided. This policy creates the following access control objects:
    An action
    The action that is created is com.ibm.commerce.sample.commands.MyNewControllerCmd
    An action group
    The action group that is created is MyNewControllerCmdActionGroup. This action group contains only one action: com.ibm.commerce.sample.commands.MyNewControllerCmd
    A resource category
    The resource category that is created is com.ibm.commerce.sample.objects.BonusResourceCategory. This resource category is for the Bonus entity bean.
    A resource group
    The resource group that is created is BonusResourceGroup. This resource group only contains the preceding resource category.
    A policy
    The policy that is created is AllUsersUpdateBonusResourceGroup. This policy allows users to perform the MyNewControllerCmd action on the Bonus bean only if the user is the "owner" of the bonus object. For example, if the user is logged on as the tester@mycompany user, the user can only modify their own bonus points.

    Setting up the AllUsersUpdateBonusResourceGroup policy involves the following steps:

    • Modifying the access control policies to reflect your environment.
    • Loading the SampleACPolicy.xml file using the acpload command.
    • Loading the SampleACPolicy_en_US.xml description using the acpnlsload command.
    1. Determine the member ID value for your Madisons store:
      1. Start the test environment.
      2. In a Web browser, open the following URL: http://localhost/webapp/wcs/admin/servlet/db.jsp
      3. Enter the following SQL statement: select member_id from storeent where storeent_id=storeent_ID; where storeent_ID is the store entity ID for your Madisons store.
      4. Click Submit Query
    2. Navigate to WCDE_installdir\xml\policies\xml and make a copy of the SampleACPolicy_template.xml file, named SampleACPolicy.xml, and a copy of the SampleACPolicy_template_en_US.xml file called SampleACPolicy_en_US.xml.
    3. Using a text editor, open the SampleACPolicy.xml and SampleACPolicy_en_US.xml files and replace all occurrences of ConsumerDirectMemberId with the member ID value for your consumer direct store, as determined in the previous step.
    4. Save the files.
    5. Stop the test environment.
    6. At a command prompt, switch to the WCDE_installdir\bin directory.
    7. Load the SampleACPolicy.xml and SampleACPolicy_en_US.xml files:
      • For IBM i OS operating systemDB2Oracle Run the following commands:
        
        acpload db_name db_user db_password inputXMLFile SCHEMA_NAME
        acpnlsload db_name db_user db_password NLSinputXMLFile SCHEMA_NAME
        
        Where
        db_name
        is the name of your database
        db_user
        is your database user name
        db_password
        is your database password
        inputXMLFile
        is the name of the XML file containing the policy. In this case, enter SampleACPolicy.xml.
        NLSinputXMLFile
        is the name of the National Language XML file containing the policy description. In this case, enter SampleACPolicy_en_US.xml
        DB2OracleSCHEMA_NAME
        is the database user name or the user who owns the WebSphere Commerce schema.

        For example, you can issue the following command:

        
        acpload dbuser dbuser SampleACPolicy.xml dbuser
        acpnlsload dbuser dbpasword SampleACPolicy_en_US.xml dbuser
        
      • Apache DerbyRun the following commands:
        
        acpload SampleACPolicy.xml
        acpnlsload SampleACPolicy_en_US.xml
        
  7. Modifying the MyNewJSPTemplate.jsp page to include bonus points
    1. In Rational Application Developer, switch to the Web perspective.
    2. Expand Stores > WebContent > Madisons
    3. Open both the MyNewJSPTemplate_All.jsp and MyNewJSPTemplate.jsp files.
    4. Copy Section 9 from the MyNewJSPTemplate_All.jsp file into the MyNewJSPTemplate.jsp file to introduce the following text into the JSP page:
      
      <!-- SECTION 9 -->
      
      <h2><fmt:message key="BonusAdmin" bundle="${tutorial}" /> </h2>
      
      <c:if test="${!empty taskOutputUserId}">
        <ul>
          <li> 
            <b>
            <fmt:message key="PointBeforeUpdate" bundle="${tutorial}" />
            <c:out value="${oldBonusPoints}"/>
            </b>
          </li>
          <li>
            <b>
            <fmt:message key="PointAfterUpdate" bundle="${tutorial}" /> 
              <c:out value="${bdbInstance.bonusPoint}" />
              </b>
            </li>
        </ul>
      </c:if>
       
      
      <br />
      <b><fmt:message key="EnterPoint" bundle="${tutorial}" /></b><p />
      
       
      <form name="Bonus" action="MyNewControllerCmd">
      <table>
        <tr>
          <td>
            <b>Logon ID </b>
          </td>
          <td>
            <input type="text" name="input1" value="<c:out 
              value="${userName}"/>" />
          </td>
        </tr>
        <tr>
          <td>
            <b>Bonus Point</b>
          </td>
          <td>
            <input type="text" name="input2" />
          </td>
        </tr>
        <tr>
          <td colspan="2">
            <input type="submit" />
          </td>
        </tr>
      </table>
      </form>
       
      <!-- END OF SECTION 9 -->
      
    5. Save the MyNewJSPTemplate.jsp file.
  8. Testing the integrated Bonus bean. Since the new Bonus bean is protected under access control and users can only execute the MyNewControllerCmd action on a bean that they own, the user must log in. As such, you will use the login feature in your starter store to allow the user to log in.
    1. Start the test environment
    2. Navigate to the Stores > WebContent > Madisons directory.
    3. Select the index.jsp and from its pop-up menu, select Run As > Run on Server.
    4. Login to your Madisons store as a registered user, enter the Logon ID for the user that you created in Testing user name validation.
    5. Once the login completes, enter the following URL in the same browser: http://localhost/webapp/wcs/stores/servlet/MyNewControllerCmd?input1= logon_id&input2=2000
    6. where logon_id is the logon ID for the user that you created in Testing user name validation. A page that contains all of the previous output parameters displays as well as a new form that allows you to update the balance of bonus points for the user.
      Note: If global security (LDAP) is enabled, instead of the logon_id, you need to use the name registered in the LDAP server. This name must be properly URL encoded. For example, if the name registered to the LDAP server is uid=myName,cn=users,dc=ibm,dc=com, the URL encoded LDAP string is: uid%3DmyName%2Ccn%3Dusers%2Cdc%3Dibm%2Cdc%3Dcom.

      Screen capture of Bonus Administration form.

      Now, enter the user's logon id into the Logon ID field and enter 500 in the Bonus Point field. Click Submit. A page similar to the following one displays that shows that the updated balance of bonus points.

      Screen cap of Bonus Administration form with updated bonus points shown.

Results