Friday, September 30, 2016

Installing SSL Certificate in WebSphere Application Server

In certain cases, when you integrate your application with third party services, you might have encountered hand shake error while trying to connect with the service. To resolve the error, we need to install the certificate provided by the third party in our application server. Below are the steps to be followed to install the certificate in Websphere Application Server.

1. Login to Administrative Console of WAS.

2. Expand the section "Security" in the left hand side and select "SSL certificate and key management".


3. From the page displayed above, click on "Key stores and certificates" option in the right hand side  under "Related Items" heading.



4. Click on NodeDefaultTrustStore option displayed above.



5. Now click on the "Signer Certificate" link of the right hand side, which is under "Additional Properties". It will show the list of certificates already installed. Click on "Add" button on the top.


6. Mention an alias name and the path where the certificate file is present, including the certificate file name. Click Apply. The certificate will get installed in the server.


This will resolve the hand shake error.
 

Integrating WebSphere Commerce with Facebook

Many e-commerce sites are allowing customer's to login to their website using social commerce login options such as facebook, google+ etc.

OOB WCS is also providing support for connecting the e-commerce site with facebook, but the functionalities are limited to share and likes. It doesn't provide support for login using facebook account.

In this article, I will explain how to integrate facebook login option with websphere commerce. In this example, we are doing direct integration and we will not be using any third party APIs. The steps mentioned here are applicable for integrating Facebook login with simple J2EE applications too, except the last few steps.

The integration can be done in 2 ways - one is using Facebook JavaScript APIs and another one is using graph API. Though both the integrations are simple, we will be going with graph API. The reason being, in the code we need to mentioned the appId and app secret and if we are using JavaScript integration, these secrets will be visible to everybody.

As part of integration, first we need to provide an option in the front end for the user to login to facebook. This can be achieved through the following code snippet.

<%
    String fbURL = "http://www.facebook.com/dialog/oauth?client_id=XXXXXXXXXXXX&redirect_uri=" + URLEncoder.encode("https://localhost/webapp/wcs/stores/servlet/en/mytestesite/processLogin?storeId=10201") + "&scope=email,public_profile";
%>
</br>
<a href="<%= fbURL %>" class="h_tnav_but" id="headerFBlogin" >Login With Facebook 
<img class="img_align" id="WC_FacebookConnectDisconnectDisplayImg_1" src="<c:out value="${jspStoreImgDir}images/socialIntegration/facebook.png" escapeXml="false" />" alt="" /></a>
</div> 

 

This snippet can be placed any JSP file, where you want to show the login button. Replace the client_id with whatever clientId you obtained after registering at Facbook developer. Once the customer click on the above button, he will be directed to Facebook login page. After login, customer will be redirected back to the redirect_uri specified in the above code.

Now, let us write the custom logic to handle the redirection from Facebook. processLogin is a controller command, which is mapped in struts-config-ext.xml file. The main functionality of this code is to authenticate our application with Facebook, retrieve whatever customer details we required, check whether the customer is an existing customer and proceed with login/registration accordingly.

In processLogin command, first we need to confirm our authenticity with Facebook and fetch the auth token from them. For this, invoke https://graph.facebook.com/oauth/access_token API by passing client_id (which is same as appID), client_secret and the code which we received through URL from Facebook as part of redirection.

Once we get the access token from Facebook, invoke https://graph.facebook.com/me API to retrieve the details we require by passing this access token. Whatever information we need from Facebook should be mentioned in the request. A sample request is given below.

https://graph.facebook.com/me?fields=id,name,first_name,last_name,email,gender,link,locale,timezone

The above request will retrieve id, name, firstname, lastname, emailed, gender etc. of the customer. Now, we can add our logic on how to handle this details.

Using the below snippet, we can check whether the customer is an existing customer or not.

UserRegistryAccessBean userAB= UserRegistryCache.findByUserLogonId(strLogonId);

If the customer is an existing customer, we can invoke the OOB logon command to login the user to our website. If the user doesn't exist, first check whether you have received all the mandatory parameters required for registering at your site from Facebook, and if everything is there, assign it to request properties and invoke UserRegistrationAddCmd.

Now, customer's can login to your site through social login options.

During integration, you may encounter issue with SSL certificate as Facebook is using oauth mechanism and HTTPS for handshaking. Refer my post  for how to download and install the certificate in WebSphere server. 
 
 

Wednesday, September 28, 2016

Packages in Java

Packages:

Packages are nothing but folder structure, inside that we will create our java classes.
Classes with related functionality are bundle together in the same packages.
If you put all files of a project to a single package, it will be very difficult to manage the files.

Advantages of Packaging.
  • .       Better development and Organization of files:
Packaging helps to organize files in your project. You can arrange all Java classes with similar functionality to one folder.

E.g 1
          Java libraries are arranged in such way that , 
                           all I/O related functionality put inside  -> java.io package
                           Network related functionality put inside -> java.net
E.g
         If you are developing a shopping cart application we want different modules like
ProdcutDisplay, Promotions , ItemsPage, Checkout. 
So during development If we put each modules under each packages then it will be easy to develop and organize.

                  abc.shoppingCart. ProdcutDisplay
                  abc.shoppingCart. Promotions
                  abc.shoppingCart. Checkout

If 3 people are working on this project so that they can develop each module independently.
  • .       Resolve name conflict:

            Packaging helps to resolve name conflicts, if different packages have classes with same name.
Every class contained in a package has a unique name that cannot conflicts with class names defined in another packages.

E.g 
2 companies A & B are developing shopping cart application and they used identical name for their checkout classes.
If they have used the packaging then name conflict will not happen.

A. shoppingCart. Checkout
B. shoppingCart. Checkout

Creating Packages in Java Programs:

Package is creating in java with ‘package’ keyword , which is the first keyword in any java program followed by import statements.

package com.abc.shoppingcart;


If we want to use method of java classes you have to import that. Java.lang package in imported implicitly by default.

Tuesday, September 27, 2016

Simple Steps for Creating Custom Widget in WCS 8


In one of my earlier post (http://myjavakitchentime.blogspot.com/2015/11/creating-new-commerce-composer-widget.html), I have detailed the steps for creating a custom widget in WebSphere Commerce 7. In this post, I will be explaining how to create a simple widget in WebSphere Commerce 8. Though there is no much difference between the steps, I have simplified this post to help a new comer to easily understand how to create a custom widget by following the below simple steps.

The steps are given below.
 

1.     Create a new project in your WebSphere Commerce Developer workspace
 

a.     Right-click within the Enterprise Explorer view. Select New > Project.

b.     In the New Project wizard, expand General. Select Project. Click Next.

c.     For the Project name field, enter a name for the temporary project. For example, NewWidgetProject.

d.     Click Finish.
 

2.     Create the input pattern file

a.     Right-click the temporary NewWidgetProject project. Select New > File.

b.     In the New File wizard, ensure that your temporary project is selected as the parent folder. Enter a File name for the pattern input XML file. For example, NewWidgetPatternInputFile.xml.

c.     Click Finish.

d.     Right-click your new pattern input XML file within your temporary project. Select Open With > XML Editor.
 

Copy the following code into the file:
 

<pageLayout vendor="myCompany" targetFolder="NewWidgetProject">
  <widget>
    <widgetDef identifier="myNewContentRecommendationWidget" 
     UIObjectName="myNewContentRecommendationWidgetObject"
     displayName="My New Content Recommendation Widget"
     description="This widget displays marketing content, such as ads, on a store page"
     widgetDisplayGroups="AnyPage,SearchPage"
     widgetRestrictionGroups="AnyPage,SearchPage" >
      <property name="widgetOrientation"
       displayName="Widget Orientation"/>
      <property name="numberOfContentToDisplay"         
       displayName="Maximum number of content to display"/>
    </widgetDef>
    </widget>
</pageLayout>
 

 
3.     Run Jet transformation

a.     Right-click your pattern input XML file. Select Run As > Run Configurations.

b.     In the Run Configurations wizard, double-click JET Transformation from the list of filters. The configuration options for the JET Transformation display.

c.     Ensure that the value of the Name field is the name of your pattern input XML file.

d.     In the Main tab, ensure that the value of the Transformation Input field is the file path within your workspace to the pattern input XML file. For example, NewWidgetProject\NewWidgetPatternInputFile.xml

e.     In the Transformation section, select com.ibm.commerce.toolkit.internal.pattern.pageLayout for the value of the ID field.

f.      Optional: Specify the severity level for the Display Message logging. The default value is information.

g.     Click Apply > Run

 

You can see that new folders with names DataLoad, Stores and LOBTools got generated inside your new project (ie, inside NewWidgetProject folder in this example).

 
Given below is a sample folder structure which got generated after JET transformation.

 

4.     Move the generated files and folders to WCS default project locations.
 

a.     Copy the Widgets-test folder which is present under NewWidgetProject -> Stores ->WebContent to Stores ->WebContent folder. Modify the JSP file, if you want to display some content/custom message in the front end.

b.     Copy the test folder which is present under NewWidgetProject  -> LOBTools -> src -> com to LOBTools -> src -> com folder

c.     Copy the test folder present under NewWidgetProject  -> LOBTools ->WebContent -> WEB-INF -> src -> xml to LOBTools ->WebContent -> WEB-INF -> src -> xml folder.

5.     Open wc-dataload-env.xml file and modify the database connection parameters.
 

6.     Execute the dataload utility as follows.

Dataload.bat C:\IBM\WCDE80\workspace\< NewWidgetProject>\DataLoad\widget\wc-dataload-widget.xml

Replace < NewWidgetProject> with the name of the custom project that you have created as part of widget creation. In this example, it is NewWidgetProject.

When prompted for store identifier, provide the SAS store identifier.
 

7.     Refresh the projects and restart the server once. You should be able to see the newly created widget in your CMC
 
Note: Follow this approach for creating simple widget for learning purpose for the first time. If you are creating the widget for second time, using the same vendor name (in this example “myCompany”) used earlier, you need to merge the files in Stores & LOBTools folder instead of copy pasting the folders.

Sunday, September 18, 2016

Don’t use Double Brace Initialization – double curly braces Anti pattern


·      -   Double brace initializer is nothing but it is instance initializer inside a inner class.
·      =  Double Brace Initialization looks convenient for variable initialization for collections (map,List,set..). This feel good, because we can declare and initialize collections at the same time.
·        This means we can declare and initialize at the same time using instance initializer.
E.g we a list and we want to add some elements to this like "A","B","C". What we will do.
List<String> list = new ArrayList<String>(); 
list.add("A"); 
list.add("B"); 
list.add("C"); 
Also we can initialize as below. But this is a unmodifiable list, if we try to modify this list, it will give java.lang.UnsupportedOperationException

List<String> listOfLetters1 = Arrays.asList("A", "B", "C"); 
                         
Initialize using Double braces:
List<String> list = new ArrayList<String>()
{
{
add("A"); 
add("B"); 
add("C"); 
}
};
It’s look pretty and simple,  we can do initialization in one line.


What is Double Brace Initialization?
·        Double brace initializer is nothing but it is instance initializer inside a inner class.

instance initializers to instantiate collections
instantiating and initializing collections without having to manually populate the list.
Declaration and initialization in one line.
This is not a special {{ symbol but two { given different meanings. The first { shows this is an anonymous class, the second { means the start of an initializer block.
How the compiler will consider this? or why it is saying avoid this ? or why it is calling as anti pattern ?
·        Creating anonymous class while compilation – that decrease the performance.

Double brace initializer is just a initializer inside (inner braces) anonymous inner class(outer braces).
The outer ‘{ ‘ represent anonymous  inner class
So every time when we are creating a map or any collection using double brace initializer means your creating an anonymous inner class.

At run time compiler will generate *.class file for each anonymous inner class and that will loaded and invoked by class loader at runtime.
e.g>
public class test  {
public test {

List<String> list = new ArrayList<String>() {{
add("A"); 
add("B"); 
add("C"); 
}};
}
public static void main(String[] args) {
        new test();
    }
}

For the above example after compilation this will be having test.class, test$1.class
i.e for every anonymous inner class a ‘.class’ file will be gnereating.

So at the run time class loader will invoke this, this will reduce overall performance of your application.

·        Inner classes Keeping a ‘this’ reference to the outer classes- creating memory leak
For non-static anonymous inner classes that will always keep reference to their enclosing instance. .i.e the inner class always have ‘this’ reference (this$0) to the outer class. This will lead to memory leak- since this is preventing GC from freeing up the occupied memory.
That is to, serialize the collection you have to serialize the entire enclosing class.
·        Doesn’t support empty  diamond operator (<>)
From Java 7 onwards, we will be to declare variables using <>,
List<String> list = new ArrayList< >(); 
But double brace intializrer is not supporting this.
List<String> list = new ArrayList< >()
{
{
add("A"); 
add("B"); 
add("C"); 
}
};
The above code will throw compilation error.
Because of the above all disadvantages, we are not using double brace initializer nowadays, so this become an antipattern.
Where to use:  Used only for testing, demos and debugging.
In Java 8 we have  Stream API and Collectors available for initialization of collections.
List<String> list = Collections.unmodifiableList(Stream.of(("A", "B", "C").collect(toList()));
But the streams collectors make no guarantees about the mutability of collections they return

Displaying Dynamic E-spots Using Web Activity

In my previous post, I have explained how to configure page specific e-spots through management center by modifying widget configuration. In this post, I will explain how the similar functionality can be achieved by making use of Web Activity in Websphere commerce.

As most of you know, web activities are available in Marketing section of Commerce composer tool through which we can configure various triggers, targets and actions to display dynamic contents in the store front. It is one of the power tool which can provide targeted personalized content to the end user in commerce.

Using web activity, we can configure e-spots to display different contents to the customer based on which page customer is viewing.

First I will show you the custom web activity created for displayed page specific espots and will explain you each of the components.



Similar to any web activity in WCS, first we need to create a dummy E-marketing spot which need not have any content assigned to it. Whenever you select a new "web activity" option in management center -> Marketing section, by default an E-Marketing spot icon will be added in the activity.

Click on the E-Marketing spot icon and one configuration section will get opened below. In the configuration section, select the name of the dummy E-Marketing spot that you have created.

From the branching section present in the left side (as you can see in the above image), choose one of the branch icon and drag it to the line in the main screen after the e-spot.

Similarly, from the Targets section in the left hand side, select "current page" icon and drag it to both the branches. Same way, drage the "Recommend Content" icon from "Actions" section to the main screen, which will create a diagram as shown above.

Now let us configure each of the icons one by one by clicking on them and modifying the configurations below.

First, click on the branch icon, and mention the path names in the configuration section. You can give any name you want. In the above example, the name given is path1, path2.

Now click on the current page icon in the main screen and configure its properties as follows. Please note that you can choose any option you want to configure. In this example, we are creating activity for category page and hence selected the below option

Customer behavior: Customer is viewing a category

Target customers: Who are viewing any of the following categories

Categories : select the category to which the dynamic content to be applied. Select different category names based on the branch in which you are configuring this "current page" icon.

Click on "Recommend Content" icon. Select the category specific content that need to be displayed.

One last step is to insert the newly created dummy e-spot in the category page layout. You can follow the same steps that I mentioned in my previous post except that the E-Marketing Spot type should be selected as "Common e-Marketing Spot".

Activate the web activity. Now, if you navigate to the category pages in the website, you can view the category specific contents in the screen.

 If you have any queries or seeking more details related to this topic, please drop an email to my id.
 

Displaying Page Specific Espots in WCS

We can create E-spots through management center to display static content/assets in different customer facing pages such as home page, category page, search result page etc. Most of the times, business users wanted to display category specific contents in various categories. For eg. if the customer is viewing a category page which lists down "chairs", business users want to display some contents specific to chairs where as while viewing "Sofa" category page, the business users might want to show Sofa related contents and promotion information to the user.

The above requirement can be achieved in two ways through the configuration in management center.

Let me first talk about configuring Dynamic E-spots through CMC using pagelayout and widget option.

With the introduction of "Commerce Composer", the browse specific page design and layouts can be completely controlled through Management Center. If we want to display an additional section in a page, we can simply drag and drop the required widget in the slot where we need to display the information to the user.

Similar way, we can insert an additional E-spot in the page layout of category page to display the page specific dynamic contents. For that,

a) Navigate to the commerce composer section in Management center (CMC). select the pagelayout in which the page specific E-Spot need to be applied. Click on the Design Layout tab as shown below.



b) Click on the slot where you want to insert the E-spot. An "AddWidgets to Slots" popup will be displayed. Scroll down and select "E-Marketing Widget" from this popup. Click OK



c) The E-spot will get inserted into the page layout and you will be taken to configure widget section as shown below. As you can see, there is an E-Marketing Spot type section where you can mention what type of widget need to be displayed. Since we are looking for a page specific dynamic espot, select the option "Page-specific e-Marketing Spot".




d) On selecting the option, the below section will be displayed where we need to specify an suffix. This suffix will be used to name the E-spot. By default, it will looks for E-spot with name [page_name][suffix]. For example,if you are configuring it for chair category page, it will look for an espot with name "chairpromoconent" (in this example).



e) Click on "Save".

Now we have to create espots for each of the pages in the format [page_name][suffix]. If the espot is not created, nothing will be displayed in the screen and user can view all the remaining widgets which are applied on the screen.

This is the simplest option of configuring page specific espots.

The other method of configuring dynamic espot will be using webactivities which I will explain in my next blog.
 

Creating sample webservice in Java

In this article, I will be explaining the steps to be followed to create a simple webservice using Eclipse. We will be using Eclipse Luna version to create the webservice.

In this example, we will create a webservice which will return "Hello World" text to the client.

The steps are given below.

1. Go to New -> Project option in eclipse.



2. From the select wizard displayed, select the option web -> Dynamic Web Project. Click Next



3. Type in a project name. In this example, we have given the project name as "HelloWorldWebService". Click Next


4. In the upcoming pages also, select the default options and proceed. From the below page, click "Finish".



5. Now a project with the given name will be created in Eclipse. Expand the "Java Resources" section and right click on "src" folder under it.




6. Choose New -> Classes option. In this example, the name of the class is mentioned as "HelloWorld" and package name as "com.test.service".


7. Write the code snippet as shown below in the newly created class.

package com.test.service;
public class HelloWorld {

 public String getHelloWorld() {
  return "Hello World";
 }
}


8. Now, right click on the class name and select WebServices -> create webservice option as shown below.




9. Click the checkbox "publish the webservice". Press next button.



10. By default the method that we have created in the Java class will be displayed. Make sure that the checkbox is selected. Click Next



11. In order for the webservice to be accessible by the clients, the server should be started and the service should be published in the server. From the below screen, click on "Start server" and then click "Finish".




12. The web service is ready now. The below screen will be displayed in Eclipse which will provide the endpoint details and parameter and response details.

It's very simple. right?

 

Saturday, September 17, 2016

Java Program: Reading from properties file

Keeping the static configuration values in a separate file is always a good idea in terms of maintainability as we just need to open that file modify the configuration value directly rather than going through the code and modify the values manually.

Given below is a sample program which shows you how to use a properties file to store the configuration values and how to read it from Java program.

First I will show you the Java program to read the contents from properties file.

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ReadFromPropertiesFile{

 public static void main (String args[]) {

  String propertyFileName = "configurationvalues.properties";
  Properties prop=new Properties();
  InputStream propertyFileStream = ReadFromPropertiesFile.class.getClassLoader().getResourceAsStream(propertyFileName);

  if (propertyFileStream != null) {

   try {
    prop.load(propertyFileStream );
   } catch (IOException ex) {
    ex.printStackTrace();
   }
   String username = prop.getProperty("username","");
   System.out.println("My username is :"+username);
  } else {

   System.out.println("Failed to read from properties file");

  }
 }
}

In this example,we have created a properties file named "configurationvalues.properties" with the below content.

username=prabheesh

Please note that properties file is nothing, but a text file which holds data in key-value format.
In the example shown above, the properties file is kept under the src directory where this java program is also present. (Note: We can keep the properties file anywhere we want, but we need to modify the classpath parameters to locate the properties file).

The above program will check whether the properties file is present in the classpath. If the file is present, the contents of the file will be read into a Properties object. Once the contents are loaded, we can display the values by passing the key information to getProperty() method.

Java program to read file contents

The below Java program will read the contents from a file line by line and will print it in the screen


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFromFile {
public static void main (String args[]) {

  StringBuffer sFileContents = new StringBuffer();
  try (BufferedReader br = new BufferedReader(new FileReader("C:\\myfile.txt")))
  {
   String sCurrentLine;

   while ((sCurrentLine = br.readLine()) != null) {
    sFileContents.append(sCurrentLine);
   }
  } catch (IOException ex) {
   ex.printStackTrace();
   throw ex;
  }
  System.out.println("File content is :"+sFileContents);
 }
}

Java program to invoke a service requiring basic authentication

Most of the web applications/webservices available in the internet uses some kind of authentication mechanism to avoid unauthorized access. One of the simplest authentication mechanim used is the base64 based authentication where the client has to send the user name and password information to the webservice/web application in an encrypted format.

Given below is a simple Java program which uses basic authentication mechanism to connect to the webservice and retrieve the student information.


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

public class InvokeSampleService {

 public static void main(String[] args) {

  String authString = "my_username:my_password";
  byte[] authEncBytes = org.apache.commons.codec.binary.Base64.encodeBase64(authString.getBytes());
  String authStringEnc = new String(authEncBytes);
  try {
  
   URL url = new URL("https://api.myservice.com/student/retrieve");
   HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
   conn.setDoOutput(true);
   conn.setRequestMethod("GET");
   conn.setRequestProperty("Authorization","Basic "+authStringEnc); 
  
   if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
    throw new RuntimeException("Failed : HTTP error code : "
      + conn.getResponseCode());
   }
   BufferedReader br = new BufferedReader(new InputStreamReader(
     (conn.getInputStream())));
   String output;
   System.out.println("Output from Server ....:");
   while ((output = br.readLine()) != null) {
    System.out.println(output);
   }
   conn.disconnect();
  } catch (Exception ex) {
   ex.printStackTrace();
  }
 }
}



The my_username and my_password texts mentioned in authString assignment should be replaced with the username & password that you received from the webservice/application provider.

Simple Java Program to Invoke an OAuth webservice

OAuth is an authentication mechanism that allows an application to connect to a service on behalf of a user without sharing their password. There are several webservices exposed by third parties, which mandates client to use OAuth mechanism to connect with their service.

In OAuth mechanism, we need to pass an authentication token to the webservice, instead of username/password while invoking their service.

Below is a sample standalone Java program, which will connect to a webservice using OAuth mechanism.
 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

public class InvokeSampleService {

 public static void main(String[] args) {

  String authToken="trtry65ttfdfsfdsfdcxxewd";
  String messagetobeSent="{\"id\":\"10001\",\"name\":\"prabs\",\"totalmark\":\"79\"}";
  try {
   URL url = new URL("https://api.myservice.com/student/update");
   HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
   conn.setDoOutput(true);
   conn.setRequestMethod("POST");
   conn.setRequestProperty("Content-Type", "application/json");
   conn.setRequestProperty("Authorization","Bearer "+authToken);

   OutputStream os = conn.getOutputStream();
   os.write(messagetobeSent.getBytes());
   os.flush();

   if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
    throw new RuntimeException("Failed : HTTP error code : "
      + conn.getResponseCode());
   }

   BufferedReader br = new BufferedReader(new InputStreamReader(
     (conn.getInputStream())));
   String output;
   System.out.println("Output from Server ....:");
   while ((output = br.readLine()) != null) {
    System.out.println(output);
   }
   conn.disconnect();
  } catch (Exception ex) {
   ex.printStackTrace();
  }
 }
}


The above program will invoke student update API to update the total mark of a student.

This API used OAuth based authentication. So, as you can see in the code, the authentication token is passed to this API  using setRequestProperty() method of HTTPsURLConnection class. The auth token should be passed in the below format as mentioned in the above program.

conn.setRequestProperty("Authorization","Bearer "+authToken);

 

Customizing SMS Message contents in WCS

In the previous blog, I have explained how to configure SMS transport in WCS. If we use the OOB message types for sending SMSs, the content of the SMS will be the default one configured in WCS.

If we need to customize the SMS contents, please follow the below steps.

1. Open the OrderNotification.properties file present under WC/properties folder.

2. Search for the text "OrderSMSHeader" in this file.




3. Modify the value assigned to this property, in the way it need to be appeared in the SMS.

The SMS content is constructed using the 3 properties defined in this file - OrderSMSHeader, OrderSMSBody, OrderReceivedSMS etc. Make changes in these properties as per your requirement. During runtime, the %1 value mentioned in this property will be replaced with the order number placed by the customer.

Make similar changes language specific OrderNotification properties file present in this location  such as OrderNotification_en_US.properties file.

Configuring SMS transport in WebSphere Commerce

In E-commerce world, customers prefers to get notification SMSs in their mobile phones whenever there is an update in the orders they placed. WebSphere commerce provides an easier configuration option to integrate SMS gateways with WCS for sending SMSs. The below section explains how to configure SMS transport in WCS.

Given below is the step by step activities to be performed for the integration in your local WCS instance.

1. Login to admin console https://localhost:8002/webapp/wcs/admin/servlet/ToolsLogon?XMLFile=adminconsole.AdminConsoleLogon

2. From the top menu options, select Configuration -> Transports as shown below.



3. From the list of transports listed in this page, select SMS HTTP option and click "configure" button on the right hand side.




4. Provide the SMS gateway related information over here, including the SMS gateway endpoint/URL information and the mapping between the parameter names accepted by the gateway and WCS parameters.


In the above example, the sendMessage API accepts parameters such as message, MobileNo etc as the input. The message is mapped to "Message Key" in WCS system which will contain the SMS content to be send to the customer. MobileNo field in the API is mapped to "Receipant Key" in WCS, which holds the mobile number of the customer. (Note that the sms gateway name mentioned here is just a sample which actually doesn't exists. Please replace it with the API details of your sms gateway)

5. Save the configuration.
6. Navigate back to Configuration -> Transports option in admin console and select SMS HTTP option once again. Click "Change Status" button in the right hand side and activate the transport.


Now, let us configure the scenarios when the SMS need to be send to the user. One of the pre-defined event available in WCS for this is notifying the customer once the order is placed. Let us see how to configure the message type corresponding to this event.

1. In admin console, navigate to Configuration -> Message Types screen
2. Click on "New" button on the right side of the screen
3. select "message type" as "Message for a received order". Configure other parameters as shown in the below screen.




4. Click next. Specify the details that you have mentioned in step 4 of configuring transports above at here too and click finish.

5. Navigate back to Configuration -> Message Types screen in admin console. You can see that the newly created message type is listed on this page.

6. Click on the check box next to the message type that we newly configured and click on "change" button on the right side to activate it.

That's it. The customer will receive the SMS notifications, once the order is placed. No additional coding/customization is required for this.