Thursday, 17 May 2012

Forward View and Redirect View in Websphere Commerce


Redirect View 

In the case of redirect view when redirects from a command the View or JSP will run in a new transaction Hence if an  exception occurs in the JSP what is saved in the command won't roll back.Redirect is done via URL  and hence it can't pass objects  back to View.It can only pass name value pairs.Redirect has a browser URL length limitation with IE browser. 

There are two approaches for handling a limited length redirect URL:
1.Override the getViewInputProperties method in the controller command to return only the sets of parameters that are required to be passed to the redirect response.
2.Use a specified special character in the URL parameters to indicate which parameters can be removed from the input parameter string.
For E.g.: While redirecting to TestViewName we need to remove certain parameters due to URL length limitation. In this case property2, property3 has to be removed.

URL="TestViewName";
Property1=" PropertyValue1";
Property2=" PropertyValue2";
Property3=" PropertyValue3";

Using Approach 1 (Override the getViewInputProperties method)

If you are overriding the getViewInputProperties method, the new method can be written so that only the following parameters are passed to the view command:

Property1="PropertyValue1";

public TypedProperty getViewInputProperties() {
TypedProperty tp = viewReqProperties;
tp.remove(Property2);

tp.remove(Property3);
return tp;
}


Using the second approach(Use special character to indicate which parameters can be removed), consider this URL=”TestViewName?Property2*=&Property3*="

This URL parameter instructs the Web Sphere Commerce runtime framework of the following:
The Property2*= specification means that all parameters whose names start with Property2 should be removed.
The Property3*= specification means that all parameters whose names start with Property3 should be removed.
TypedProperty rspProp = new TypedProperty();
rspProp.put(ECConstants.EC_URL, "TestViewName");
rspProp.put(ECConstants.EC_VIEWTASKNAME, ECConstants.EC_GENERIC_REDIRECTVIEW);

ForwardView

In the case of forward view when we are forwarding from a command to a View or a JSP the command and the JSP will run in the same transaction.Hence if an exception in JSP will cause what is saved in command to roll back.Forward View method can pass objects back to the view.

TypedProperty rspProp = new TypedProperty();
rspProp.put(ECConstants.EC_VIEWTASKNAME, "TestViewName");        

Note: If you use forward view while passing control from a command to a view then if user presses refresh button or F5 the command will be executed again as the URL will remain the same command URL for e.g. While passing control from OrderItemAddCmd to a view. Then when user presses F5 button one more item might be added to cart. But in the case of redirect since the URL is changed to the view URL even if user presses F5 button only the view will be loaded again.




Session Beans/ Entity Beans/JDBC helpers in Websphere Commerce


Use Websphere Commerce uses session beans when we want to read data from multiple tables.
 
Session bean should extend the  com.ibm.commerce.base.helpers.BaseJDBCHelper class. The superclass provides methods that allow you to obtain a JDBC connection object from the data source object used by the WebSphere Commerce Server, so that the session bean participates in the same transaction as the other entity beans. The following is an example of code to demonstrate the functions provided by the superclass:

public class  TestSessionBean extends com.ibm.commerce.base.helpers.BaseJDBCHelper 
implements SessionBean{
public Object  fetchResults()       throws javax.naming.NamingException, SQLException
{
try {
// get a connection from the WebSphere Commerce data source
makeConnection();
PreparedStatement prepStatement = getPreparedStatement( "sql ");
ResultSet rs = executeQuery(prepStatement, false);
}
finally {
closeConnection();
}
}
}

It is highly recommended to use EJB's for any insert\updates for the overall integrity of the data in commerce but ServerJDBCHelperAccessBean can be used in several scenarios when required to insert\update tables outside of EJB's and also do selects from multiple tables. Also the flush() method is used to flush the cache in EJB container for the DB updates.

This Internally uses prepared Statement but you don't have to map each param and could send an array of params to the execute Query method in the same order as query.
 
import java.util.Vector;
import com.ibm.commerce.base.objects.ServerJDBCHelperAccessBean;
public class TestHelper {
ServerJDBCHelperAccessBean jdbcHelperObj = new ServerJDBCHelperAccessBean();

Vector databaseRows = new Vector();
databaseRows = jdbcHelperObj.executeParameterizedQuery(query, params);
for(Object obj:databaseRows) {
Vector EachRow=(Vector)obj;
String  partNumber= (String)EachRow.get(0);
Timestamp timeCreated = (Timestamp)EachRow.get(1);
}

Note: If you are using  it to update a row in DB, do make sure to update the OPT Counter value. But updating rows using  ServerJDBCHelperAccessBean is not recommended instead make use of EJB.

Business Context In WCS

Business Context Service can be used instead of Http session or Cookies. Business Context Service option is available for maintaining the information throughout the user activity and invalidating it when the user logs out or the browser is closed.

It uses a couple of tables CTXDATA and CTXMGMT, to manage the context. Essentially each time a user comes to the site, a new activity is created in CTXMGMT table and it associates the calling user (Users_id as CALLER_ID) with an ACTIVITY_ID . The ACTIVITY_ID remains the same in the course of the session and it also keeps all the contexts associated with the activity in CTXDATA table.

When the same user logs in from a different device or a separate browser, essentially the previous context in CTXMGMT is marked as T (Terminated). It creates a new activity with a state A (Active).

CTXMGMT -This table contains the management information of each context service activity.
CTXDATA -This table contains the data that associates with a particular activity.

WebSphere Commerce configuration file (wc-server.xml) business context files are defined as follows.

<BusinessContextService
BusinessContextConfigFile="config/businessContext.xml,config/com.ibm.commerce.catalog/wc-business-context.xml,config/com.ibm.commerce.store/wc-business-context.xml,config/com.ibm.commerce.giftcenter/wc-business-context.xml" display="false">
<ExpiryManagement ExpiryMgmtChannelId="-2,-4"
InactivityTimeout="30" Threshold="30" enable="true"/>
</BusinessContextService>

Business Context configuration file

Business contexts are defined in the xml/config/businessContext.xml file.

In the configuration file, there are two major sections.

1)BusinessContexts - This section defines the different business contexts that are available to the site

<BusinessContext ctxId="BaseContext"
factoryClassname="com.ibm.commerce.context.factory.SimpleBusinessContextFactory" >
<parameter name="spiClassname" value="com.ibm.commerce.context.baseimpl.BaseContextImpl" />
</BusinessContext>

2)InitialBusinessContextSets- This section defines the business context set which is a logical grouping of business contexts for a particular type of request.
If no business context set is defined for the request, the default business context set is used.

<InitialBusinessContextSets activeCtxSetId="Default" >

< !-- default configuration -->
<InitialBusinessContextSet ctxSetId="Default" >
<InitialBusinessContext ctxId="BaseContext" createOrder="0" />
<InitialBusinessContext ctxId="EntitlementContext" createOrder="1" />
<InitialBusinessContext ctxId="GlobalizationContext" createOrder="1" />
<InitialBusinessContext ctxId="AuditContext" createOrder="1" />
</InitialBusinessContextSet>

ctxId
A required attribute that identifies the business context within the configuration file.This identifier is necessary when defining contexts within a business context set.

For ctxId ,the following attributes can be specified:

BaseContext
This context contains the basic attributes that an activity needs, such as store ID, caller ID, and the run-as ID.

<BusinessContext ctxId="BaseContext"
factoryClassname="com.ibm.commerce.context.factory.SimpleBusinessContextFactory" >
<parameter name="spiClassname" value="com.ibm.commerce.context.baseimpl.BaseContextImpl" />
</BusinessContext>

Other than base contexts WebSphere Commerce predefines the following contexts

EntitlementContext
This context holds information about entitlement criteria, such as reduced prices for gold club membership.

GlobalizationContext
This context helps components determine locale-specific information such as what language a message should be rendered in,or what currency should be used in the calculation of a price.

ContentContext
If Workspaces are enabled, this context determines the content or business objects that can be displayed or edited based on versioning information.

TaskContext
If Workspaces are enabled, this context determines which task an administrator is currently performing.

AuditContext
AuditContext is usually provided by third party components. This context enables you to connect to a different vendor's implementation of the service in the future without the need to rewrite your component.

PreviewContext
PreviewContext is the attempt by allowing multi-users to validate independent content without influencing other users and ensuring the content does not required additional changes after validation.

ExperimentContext
ExperimentContext is used to store the result of all active experiments for individual users and the result is a system-generated number which determines the control or test element to be selected in the experiment. This information is persisted throughout the user session, so the same result will be used in the same session without re-generation of the number.

CatalogContext
CatalogContext contains information related to the catalog in the current session, such as the catalog ID, the catalog owner, and whether this is a master catalog or not.

GiftRegistryContext
GiftRegistryContext contains gift registry information for a user in the current session, such as a list of gift registries that the user has accessed, the relationship the user has to specific gift registries (gift giver, registrant or coregistrant), and the external ID of the gift registry the user is currently managing.

Defining business context sets for a Web application

Steps to be followed

Step 1) Open the WebSphere Commerce configuration file in an editor.
Set the contextSetName attribute within the Module element. For example, to enable the CommerceAccelerator webapp to use the Authoring business context:

<Module
contextPath="/webapp/wcs/tools"
fileServletEnabled="false"
name="CommerceAccelerator"
urlMappingPath="/servlet" webAlias="/wcs">
<InitParameters adapters="BrowserAdapter" contextSetName="Authoring"/>
</Module>

The predefined business context sets defined in the business context configuration files are:

Default
Defines the minimum set of business contexts. Use Default when the context set does not belong to a Web application for example, MQ requests, or Sales Center requests. This is the default context set as specified by the activeCtxSetId attribute in the BusinessContext.xml file
Store
Defines the business context set for requests that come through the Store webapp. For example, catalog browsing, and order processing through the storefront.
Authoring
Defines the business context set for requests that come through the Accelerator webapp. This context set supports content management and preview capabilities.
Administration
Defines the business context set for requests that come through the Administration webapps (Orgadminconsole and Adminconsole). This context set supports administering the site.

Step 2) Save and close the file. Restart WebSphere Commerce.

How to create a Custom Business Context Service /Business context Service Customizations

Please follow the below steps for Business Context Service customization

1.First create a new Interface for the custom context by extending the com.ibm.commerce.context.base.Context interface.
2.Create a context implementation class that implements the custom interface created by extending the com.ibm.commerce.context.baseimpl.AbstractContextImpl.
3. Registering new Business Context by making an entry in businessContext.xml or Create a new businessContext.xml (Recommended  Approach).
4. Register this new businessContext.xml in the wc-server.xml under the BusinessContextService element.
5.Based on the customer requirement put the the values from the controller command or View into the context and then use the values across the application.