Sunday, September 18, 2016

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.

 

Wednesday, August 3, 2016

Java is passing object reference by value or reference ?

What is Pass by Value and Pass by reference?

These are the two way for passing parameters to the method or functions in programming languages.

Pass by Value or call by value

If we call a method by passing values to it, it is known as call by value.
 Whatever changes you are doing in the called method, will not affect the calling method.(unless and until you return that value from the method).

i.e In case of call by value original value is not changed

E.g

Public class passByValue {
Public static Void increment(int i)
{
            i =  i + 1; // i =11;
}

Calling part:

public static void main(String[] args) {      
int  i  = 10;
            increment(i);
            System.out.println(" i: " +i  ); // i  = 10;
}

Here value of ‘i ‘remain constant in outside increment. That is we are just passing values to the method.

Pass by Reference :

In the pass by reference we are passing the reference (reference to memory location) of the object not the value. So the calling parameter and method arguments both are pointing to same memory location, so change made to the values will affect both the caller and callee.
i.e In case of call by reference original value is changed if we made changes in the called method

In java there is no Pass by Reference , But for c and c++  there are Pass by Reference ,so taking the example from c to explain

E.g from C. – swap variables.

void swap(int *x, int *y) {

               int temp;
               temp = *x;    /* assigning temp to address of x */
               *x = *y;      /* assign x to y */
               *y = temp;    /* assigning y to temp */
             
               return;
            }
int main () {

               /* local variable definition */
               int a = 30;
               int b = 50;
             
               printf("Before swap, value of a : %d\n", a );
               printf("Before swap, value of b : %d\n", b );
               /* * &a ->  address of variable a
                  * &b ->  address of variable b.
               */
               swap(&a, &b);
               printf("After swap, value of a : %d\n", a );
               printf("After swap, value of b : %d\n", b );
             
               return 0;
            }
O/P :

Before swap, value of a :30
Before swap, value of b :50
After swap, value of a :50
After swap, value of b :30

In the above example we will be able to see the how to do a pass by reference. By passing ‘&a’ we are passing the reference of the ‘a’(address location of the a), so whatever changes made to this ‘a’ will reflect to the memory location. So if we don’t return also the same will reflect for calling program also.

But we know that in java there is no concept of pointers and passing the variables with ‘&’. So there is no concept of pass by reference in java.

There Exists only Pass by value in JAVA

In java we can do only pass by values (call by values) and passes the references by value.
If it is primitive type or if it is an object, everything we are passing to functions using values.

Java passes the references by value.

While hearing this, java don’t have pass by reference, we will be quite surprised!!!! Because every time we are hearing only, object , reference and instance in java, also  all object variables are references. But java doesn’t pass method parameters by references, it passes that by the references by value.

"Java manipulates objects 'by reference,' but it passes object references to methods 'by value.'" – From O'Reilly's Java in a Nutshell by David Flanagan

In java they are 2 types of parameters we are passing to the methods.

                     Primitive data types and Reference data types.

Primitive data type in Java are passed by value.
Reference data types are passed by object references by value

For Primitive we have already seen example in pass by value.

Pass object references by value – using Reference data types

Java copies and passes the reference by value, not the object. 

But these passed reference are just copies of the object references, not the original Object.

public class Employee {
            int number;
            String name;
            public static void increment(Employee emp) {
                        emp.number = emp.number +1;
            }
            public static void main(String[] args) {
                        Employee e = new Employee();
                        e.number = 1001;
                        increment(e);
                        System.out.println(e.number);
            }
}

When an object reference is passed to a method, the method gets a copy of the object reference.

So the passes and received arguments refer to same object.
Original reference and the parameter copy both will refer the same Java object.
So change in values of the reference from method reflect to both original and copy.
                                                                                                     


But from method (inside the method), we will be able to change the state of object, but that will not get reflected to the passed object, since we are passing only copy of reference.

            public static void increment(Employee emp) {
                        Employee emp1 = new Employee();
                        emp1.number = 2000;
                        emp = emp1;
                        System.out.println(emp.number);
            }

Consider the above example, here we are changing the state of object emp to emp1.So now change in emp.number will not reflect to e.number.







                                                                               

              

Value of e.number doesn’t change. But the value of Emp.number changed to ‘2000’.
That is reference by value are not actual object reference.


Swap will not work in java.

In the above in ‘Pass by Reference’ section you have seen a swap program, from C.
 But this will not work in java, since java doesn’t have pass by reference.

public class Employee {
            int number;
            String name;
            public static void swap(Employee emp1,Employee emp2) {
                        Employee temp = emp1;
                        emp1 = emp2;
                        emp2 = temp;
                        System.out.println("At the end of  swap method, value of e1.number : "+ emp1.number );
                        System.out.println("At the end of  swap method, value of e2.number : "+ emp2.number );
            }

            public static void main(String[] args) {
                        Employee e1 = new Employee();
                        e1.number = 1001;
                        Employee e2 = new Employee();
                        e2.number = 3001;
                        System.out.println("Before swap, value of e1.number :"+ e1.number );
                        System.out.println("Before swap, value of e2.number : "+ e2.number );

                        swap(e1,e2);
                        System.out.println("After swap, value of e1.number :"+ e1.number );
                        System.out.println("After swap, value of e2.number : "+ e2.number );
            }
}

O/P:
Before swap, value of e1.number :1001
Before swap, value of e2.number : 3001
At the end of  swap method, value of e1.number : 3001
At the end of  swap, value of e2.number : 1001
After swap, value of e1.number :1001
After swap, value of e2.number : 3001

From  the main() method we passed two objects e1 and e2 to swap() method and  those are received by swap() method as emp1 and emp2 references respectively. Then inside swap() method emp1  and emp2 are getting interchanged.
You will be able to see that inside the swap method both are interchanged.

At the end of  swap method, value of e1.number : 3001
At the end of  swap, value of e2.number : 1001

Inside the swap() , the state of object changed, so that will not reflected to the value of the reference.
So in main() program if we print after the swap() it is giving old values only

After swap, value of e1.number :1001
After swap, value of e2.number : 3001