Monday 25 March 2013

Tips to invoke EJB

1)
        xbonusEJBAccessBean.setBonusPoint(totalBonusPoints);
        try {
            xbonusEJBAccessBean.commitCopyHelper();
        } catch (Exception e) {
            e.printStackTrace();
        }
 
OR


      xbonusEJBAccessBean = new XBonusEJBAccessBean(new Long(getFoundUserId()));

Tip: You do not need to call commitCopyHelper() if you create the record using only the constructor, and do not call additional setters.


 2)
bonusAccessBean = new XBonusEJBAccessBean();
bonusAccessBean.setInitKey_memberId(new Long("111"));
bonusAccessBean.refreshCopyHelper();

Use the refreshCopyHelper method to retrieve information from the database and populate the access bean. You do not need to use the refreshCopyHelper() if you are using a getter method to retrieve specific data from the access bean. You only need to use it to explicitly tell the access bean to populate itself, for example, to check if the data you are looking for exists, or to populate an object before passing it to another method.

Note: When instantiating an access bean, you must ensure that all fields set by a setInitKey_xxx method are initialized before retrieving any data from the access bean. 

Steps to invoke EJB - using JSP

Follow the below steps to invoke EJB:


Invoke EJB (Entity Beans) - 1st step
Invoke EJB (Entity Beans) - 2nd step
Invoke EJB (Entity Beans) - 3rd step
Invoke EJB (Entity Beans) - 4th step

After following above 4 steps, we can see output in below jsp:


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><%@page
    language="java" contentType="application/xhtml+xml; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://commerce.ibm.com/base" prefix="wcbase" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt"
    prefix="fmt" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<%@ include file="include/JSTLEnvironmentSetup.jspf"%> <title>MyNewJSPTemplate.jsp</title>
</head>

<fmt:setLocale value="${CommandContext.locale}" />
<fmt:setBundle basename="${sdb.directory}/TutorialNLS" var="tutorial" />
<body><p>Hello World!.</p>
<h1><fmt:message key="WebSphereCommerceInformation" bundle="${tutorial}" /> </h1>
<h2><fmt:message key="Tutorial" bundle="${tutorial}" /> </h2>
<c:import url="${jspStoreDir}include/eMarketingSpotDisplay.jsp">              <c:param name="emsName" value="MySpot" />
</c:import>
<h3><fmt:message key="ParametersFromCmd" bundle="${tutorial}" /> </h3>
<fmt:message key="ControllerParm1" bundle="${tutorial}" />
<c:out value="${controllerParm1}"/> <br />

<fmt:message key="ControllerParm2" bundle="${tutorial}" />
<c:out value="${controllerParm2}"/> <br /> <br />
<c:if test="${mndbInstance.calledByControllerCmd}">   <fmt:message key="Example" bundle="${tutorial}" /> <br />
   <fmt:message key="CalledByControllerCmd" bundle="${tutorial}" /> <br />
   <fmt:message key="CalledByWhichControllerCmd" bundle="${tutorial}" />
   <b><c:out value="${mndbInstance.callingCommandName}" /></b> <br /> <br />
</c:if>
<fmt:message key="UserName" bundle="${tutorial}" /><c:out value="${mndbInstance.userName}"/> <br />

<fmt:message key="Points" bundle="${tutorial}" />
<c:out value="${mndbInstance.points}"/> <br />
<fmt:message key="Greeting" bundle="${tutorial}" /><c:out value="${taskOutputGreetings}"/> <br /> <br />
<c:if test="${!empty taskOutputUserId}">   <fmt:message key="UserId" bundle="${tutorial}" />
   <c:out value="${taskOutputUserId}"/> <br />
   <fmt:message key="FirstInput" bundle="${tutorial}" />
   <b><c:out value="${mndbInstance.userName}"/></b>
   <fmt:message key="RegisteredUser" bundle="${tutorial}" /> <br />
   <fmt:message key="ReferenceNumber" bundle="${tutorial}" />
   <b><c:out value="${taskOutputUserId}"/></b> <br /> <br />
</c:if>

<c:if test="${empty taskOutputUserId}">
   <fmt:message key="FirstInput" bundle="${tutorial}" />
   <b><c:out value="${mndbInstance.userName}"/></b>
   <fmt:message key="NotRegisteredUser" bundle="${tutorial}" /> <br />
</c:if>
<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>

</body></html>

Invoke EJB (Entity Beans) - 4th step

package com.ibm.commerce.sample.commands;

import com.ibm.commerce.command.ControllerCommand;

public interface MyNewControllerCmd extends ControllerCommand {
    static final String defaultCommandClassName=
        "com.ibm.commerce.sample.commands.MyNewControllerCmdImpl";
    public String getUserName();
    public void setUserName(String userName);
    public Integer getPoints();
    public void setPoints(Integer points);
}



package com.ibm.commerce.sample.commands;

import java.rmi.RemoteException;

import javax.ejb.CreateException;
import javax.ejb.FinderException;
import javax.naming.NamingException;

import com.ibm.commerce.accesscontrol.AccessVector;
import com.ibm.commerce.command.CommandFactory;
import com.ibm.commerce.command.ControllerCommandImpl;
import com.ibm.commerce.datatype.TypedProperty;
import com.ibm.commerce.exception.ECApplicationException;
import com.ibm.commerce.exception.ECException;
import com.ibm.commerce.exception.ParameterNotFoundException;
import com.ibm.commerce.ras.ECMessage;
import com.ibm.commerce.ras.ECMessageHelper;
import com.ibm.commerce.sample.databeans.MyNewDataBean;
import com.ibm.commerce.sample.databeans.XBonusEJBDataBean;
import com.ibm.commerce.server.ECConstants;
import com.ibm.commerce.user.objects.UserAccessBean;
import com.ibm.commerce.user.objects.UserRegistryAccessBean;
import com.ibm.ejb.sample.XBonusEJBAccessBean;

public class MyNewControllerCmdImpl extends ControllerCommandImpl implements
        MyNewControllerCmd {

    String userName;
    Integer points;

    AccessVector resources = null;
    //BonusAccessBean bonusAccessBean;
    XBonusEJBAccessBean bonusAccessBean;
    UserRegistryAccessBean userRegistryAccessBean;

    @Override
    public AccessVector getResources() throws ECException {

        String refNum = null;

        try {
            userRegistryAccessBean = new UserRegistryAccessBean();
            userRegistryAccessBean = userRegistryAccessBean
                    .findByUserLogonId(getUserName());
            refNum = userRegistryAccessBean.getUserId();
            System.out.println("++++++++++++++++"+refNum);
        } catch (Exception e) {
            e.printStackTrace();
        }

        bonusAccessBean = new XBonusEJBAccessBean();//new BonusAccessBean();

        if (refNum != null) {
            try {
                bonusAccessBean.setInitKey_memberId(new Long(refNum));
                bonusAccessBean.refreshCopyHelper();
                resources = new AccessVector(bonusAccessBean);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            } catch (RemoteException e) {
                e.printStackTrace();
            } catch (CreateException e) {
                e.printStackTrace();
            } catch (FinderException e) {
                UserAccessBean uab = new UserAccessBean();
                uab.setInitKey_MemberId(refNum);
                resources = new AccessVector(uab);
            } catch (NamingException e) {
                e.printStackTrace();
            }

        }
        return resources;

    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Integer getPoints() {
        return points;
    }

    public void setPoints(Integer points) {
        this.points = points;
    }

    @Override
    public void performExecute() throws ECException {
        // TODO Auto-generated method stub
        super.performExecute();

        TypedProperty resProp = new TypedProperty();

        resProp.put("controllerParm1", "Hello From IBM!!!");
        resProp.put("controllerParm2", "Have a Nice Day!!!");

        MyNewDataBean mndb = new MyNewDataBean();
        mndb.setCalledByControllerCmd(true);
        mndb.setCallingCommandName(this.getClass().getName());

        mndb.setUserName(getUserName());
        mndb.setPoints(getPoints());

        resProp.put("mndbInstance", mndb);

        MyNewTaskCmd taskCmd = null;

        try {
            taskCmd = (MyNewTaskCmd) CommandFactory.createCommand(
                    "com.ibm.commerce.sample.commands.MyNewTaskCmd",
                    getStoreId());
            taskCmd.setCommandContext(getCommandContext());
            taskCmd.setInputPoints(getPoints());
            taskCmd.setInputUserName(getUserName());
           
            taskCmd.setXBonusEJBAccessBean(bonusAccessBean);
            taskCmd.setUserRegistryAccessBean(userRegistryAccessBean);
           
            taskCmd.execute();

            if (taskCmd.getGreetings() != null)
                resProp.put("taskOutputGreetings", taskCmd.getGreetings());

            if (taskCmd.getFoundUserId() != null)
              resProp.put("taskOutputUserId", taskCmd.getFoundUserId());
           
            //BonusDataBean bdb=new BonusDataBean(bonusAccessBean);
            XBonusEJBDataBean bdb = new XBonusEJBDataBean(bonusAccessBean);
            if(taskCmd.getOldBonusPoints()!=null)
                resProp.put("oldBonusPoints", taskCmd.getOldBonusPoints());
            System.out.println("*******************"+bdb.getBonusPoint());
            resProp.put("bdbInstance", bdb);

        } catch (Exception e) {
            // TODO: handle exception
        }

        resProp.put(ECConstants.EC_VIEWTASKNAME, "MyNewView");
        setResponseProperties(resProp);
    }

    @Override
    public void validateParameters() throws ECException {
        // TODO Auto-generated method stub
        super.validateParameters();

        TypedProperty reqProp = getRequestProperties();

        try {
            setUserName(reqProp.getString("input1"));
        } catch (ParameterNotFoundException e) {

            throw new ECApplicationException(
                    ECMessage._ERR_MISSING_CMD_PARAMETER, this.getClass()
                            .getName(), "validateParameters", ECMessageHelper
                            .generateMsgParms(e.getParamName()));

        }
        setPoints(reqProp.getInteger("input2", 0));

    }

}

Invoke EJB (Entity Beans) - 3rd step

package com.ibm.commerce.sample.commands;

import com.ibm.commerce.command.TaskCommand;
import com.ibm.commerce.user.objects.UserRegistryAccessBean;
import com.ibm.ejb.sample.XBonusEJBAccessBean;

public interface MyNewTaskCmd extends TaskCommand {
    public String getInputUserName() ;
    public void setInputUserName(String inputUserName) ;
    public Integer getInputPoints() ;
    public void setInputPoints(Integer inputPoints);
    public String getGreetings();
    public void setGreetings(String greetings);
   
    public UserRegistryAccessBean getUserRegistryAccessBean() ;
    public void setUserRegistryAccessBean(
            UserRegistryAccessBean userRegistryAccessBean);
    public String getFoundUserId();
    public void setFoundUserId(String foundUserId);
   
    public XBonusEJBAccessBean getXBonusEJBAccessBean() ;

    public void setXBonusEJBAccessBean(XBonusEJBAccessBean xbonusAEJBccessBean);

    public Integer getTotalBonusPoints() ;

    public void setTotalBonusPoints(Integer totalBonusPoints);

    public Integer getOldBonusPoints();

    public void setOldBonusPoints(Integer oldBonusPoints);
   
}




package com.ibm.commerce.sample.commands;

import java.rmi.RemoteException;

import javax.ejb.CreateException;
import javax.ejb.FinderException;
import javax.naming.NamingException;

import com.ibm.commerce.command.TaskCommandImpl;
import com.ibm.commerce.exception.ECException;
import com.ibm.commerce.user.objects.UserRegistryAccessBean;
import com.ibm.ejb.sample.XBonusEJBAccessBean;

public class MyNewTaskCmdImpl extends TaskCommandImpl implements MyNewTaskCmd {

    String inputUserName;
    Integer inputPoints;
    String greetings;

    UserRegistryAccessBean userRegistryAccessBean;
    String foundUserId;

    XBonusEJBAccessBean xbonusEJBAccessBean;
    Integer totalBonusPoints;
    Integer oldBonusPoints;

    public XBonusEJBAccessBean getXBonusEJBAccessBean() {
        return xbonusEJBAccessBean;
    }

    public void setXBonusEJBAccessBean(XBonusEJBAccessBean xbonusEJBAccessBean) {
        this.xbonusEJBAccessBean = xbonusEJBAccessBean;
    }

    public Integer getTotalBonusPoints() {
        return totalBonusPoints;
    }

    public void setTotalBonusPoints(Integer totalBonusPoints) {
        this.totalBonusPoints = totalBonusPoints;
    }

    public Integer getOldBonusPoints() {
        return oldBonusPoints;
    }

    public void setOldBonusPoints(Integer oldBonusPoints) {
        this.oldBonusPoints = oldBonusPoints;
    }

    public UserRegistryAccessBean getUserRegistryAccessBean() {
        return userRegistryAccessBean;
    }

    public void setUserRegistryAccessBean(
            UserRegistryAccessBean userRegistryAccessBean) {
        this.userRegistryAccessBean = userRegistryAccessBean;
    }

    public String getFoundUserId() {
        return foundUserId;
    }

    public void setFoundUserId(String foundUserId) {
        this.foundUserId = foundUserId;
    }

    public String getInputUserName() {
        return inputUserName;
    }

    public void setInputUserName(String inputUserName) {
        this.inputUserName = inputUserName;
    }

    public Integer getInputPoints() {
        return inputPoints;
    }

    public void setInputPoints(Integer inputPoints) {
        this.inputPoints = inputPoints;
    }

    public String getGreetings() {
        return greetings;
    }

    public void setGreetings(String greetings) {
        this.greetings = greetings;
    }

    @Override
    public void performExecute() throws ECException {
        // TODO Auto-generated method stub
        super.performExecute();

        setGreetings("Hello!!!" + getInputUserName());

        int newBP = oldBonusPoints.intValue() + getInputPoints().intValue();
        totalBonusPoints = new Integer(newBP);
        xbonusEJBAccessBean.setBonusPoint(totalBonusPoints);
        try {
            xbonusEJBAccessBean.commitCopyHelper();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void validateParameters() throws ECException {
        // TODO Auto-generated method stub
        super.validateParameters();

        if (userRegistryAccessBean != null) {
            try {
                setFoundUserId(userRegistryAccessBean.findByUserLogonId(
                        getInputUserName()).getUserId());
            } catch (Exception e) {
                // TODO: handle exception
            }
        } else {
            try {
                userRegistryAccessBean = new UserRegistryAccessBean();
                userRegistryAccessBean = userRegistryAccessBean
                        .findByUserLogonId(getInputUserName());
                setFoundUserId(userRegistryAccessBean.getUserId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (xbonusEJBAccessBean != null) {
            try {
                setOldBonusPoints(xbonusEJBAccessBean.getBonusPoint());
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (CreateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FinderException e) {
                try {
                    xbonusEJBAccessBean = new XBonusEJBAccessBean(new Long(
                            getFoundUserId()));
                    xbonusEJBAccessBean.setBonusPoint(new Integer(0));
                    oldBonusPoints = new Integer(0);
                } catch (Exception e2) {
                    // TODO: handle exception
                }
            } catch (NamingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            try {
                xbonusEJBAccessBean = new XBonusEJBAccessBean(new Long(
                        getFoundUserId()));
                xbonusEJBAccessBean.setBonusPoint(new Integer(0));
                oldBonusPoints = new Integer(0);
            } catch (Exception e2) {
                // TODO: handle exception
            }

        }
    }

}

Invoke EJB (Entity Beans) - 2nd step

package com.ibm.commerce.sample.databeans;

import com.ibm.commerce.beans.SmartDataBeanImpl;

public class MyNewDataBean extends SmartDataBeanImpl {

    boolean calledByControllerCmd=false;
    String callingCommandName;
    String userName;
    Integer points;
   
    public boolean isCalledByControllerCmd() {
        return calledByControllerCmd;
    }
    public void setCalledByControllerCmd(boolean calledByControllerCmd) {
        this.calledByControllerCmd = calledByControllerCmd;
    }
    public String getCallingCommandName() {
        return callingCommandName;
    }
    public void setCallingCommandName(String callingCommandName) {
        this.callingCommandName = callingCommandName;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public Integer getPoints() {
        return points;
    }
    public void setPoints(Integer points) {
        this.points = points;
    }
}

Invoke EJB (Entity Beans) - 1st step


package com.ibm.commerce.sample.databeans;

import com.ibm.commerce.beans.SmartDataBean;
import com.ibm.commerce.command.CommandContext;
import com.ibm.commerce.datatype.TypedProperty;
import com.ibm.ejb.sample.XBonusEJBAccessBean;

public class XBonusEJBDataBean extends XBonusEJBAccessBean implements
        SmartDataBean {

    CommandContext cmdCtx;
    TypedProperty reqProp;

    String userId;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;

        if (this.userId != null)
            this.setInitKey_memberId(new Long(userId));
    }

    @Override
    public CommandContext getCommandContext() {
        // TODO Auto-generated method stub
        return cmdCtx;
    }

    @Override
    public void populate() throws Exception {
        // TODO Auto-generated method stub

        setUserId(getRequestProperties().getString("taskOutputUserId"));
        try {
            super.refreshCopyHelper();
        } catch (Exception e) {

        }
    }

    @Override
    public void setCommandContext(CommandContext cmdCtx) {
        // TODO Auto-generated method stub
        this.cmdCtx = cmdCtx;

    }

    @Override
    public TypedProperty getRequestProperties() {
        // TODO Auto-generated method stub
        return reqProp;
    }

    @Override
    public void setRequestProperties(TypedProperty reqProp) throws Exception {
        // TODO Auto-generated method stub
        this.reqProp = reqProp;
    }

    public XBonusEJBDataBean() {
        super();
        // TODO Auto-generated constructor stub
    }

    public XBonusEJBDataBean(XBonusEJBAccessBean bAB) {

        try {
            super.setEJBRef(bAB.getEJBRef());
        } catch (Exception e) {

        }
    }

}

Saturday 16 March 2013

Generate the Access Bean for the EJB

The following diagram displays the interaction between commands, access beans, entity beans, and the database.











Below are the steps to create AccessBean for EJB:

Right click on WebSphereCommerceServerExtensionsData -> New -> Other -> EJB -> AccessBean

























 After click on Prepare for Deployment - below are the list of java classes gets generated:


Generate the EJB to RDB Mapping

Below are the steps we need to follow to map between EJB and Database





















































 Drag and drop XBonusEJB from left panel to right panel XBONUS

















Then drag and drop all the attributes from left panel to right panel- This creates the relation between EJB and Database.























change DB2ADMIN TO NULLID -> this is require to make ejb as schema independent
























Edit the methods of the bean class XBonusEJBBean to call optimistic locking classes:



     /**
     * ejbLoad
     */
    public void ejbLoad() {
        super.ejbLoad();
        _initLinks();
    }

    /**
     * ejbStore
     */
    public void ejbStore() {
        super.ejbStore();
    }

Friday 15 March 2013

Modify EJB methods and Finders


1) Open XBonusEJBBean java class, we need to overload ejbCreate(...) method and mention the same in Home interface, also add fullfill(...) and getOwner() methods:


    public com.ibm.commerce.extension.objects.BonusKey ejbCreate(
            long memberId, Integer bonusPoint)
            throws javax.ejb.CreateException {
   
        this.initializeFields();
        _initLinks();
   
        this.memberId = memberId;
        this.bonusPoint = bonusPoint;
   
        XBonusEJBKey aKey = new XBonusEJBKey(memberId);
        this.initializeOptCounter(aKey);
   
        return null;
    }
   
    @Override
    public Long getOwner() throws Exception {
        // TODO Auto-generated method stub
        return memberId;
    }
   
    @Override
    public boolean fulfills(Long member, String relationship) throws Exception {
   
        if("creator".equalsIgnoreCase(relationship)){
            return member.equals(memberId);
        }
        // TODO Auto-generated method stub
        return false;
    }
 


2) Delete below 3 methods:



















3)Add finders to the EJB - > double click on deploymenent descriptor and go to Bean tab (at bottom) and do the following configuration:









Next we need to Generate the EJB to RDB Mapping