Sunday, July 24, 2016

WCS - Adding new currency support

By default, Websphere Commerce doesn't provide an option to use Indian Rupees as the currency. But while customizing WCS for Indian customers, supporting Indian currency is necessary. Follow the below steps to enable INR as one of the currency option in the WCS based website.

Step 1. Configure INR as one of the currency: For this, execute the below SQLs in database.

-- To create currency
INSERT INTO SETCURR (SETCCURR, SETCCODE, SETCEXP) VALUES ('INR', 35, -2);

-- To add description to a currency in site level
INSERT INTO SETCURRDSC VALUES ('INR', -1, 'Indian Rupees', NULL);

-- To add currency format rule
INSERT INTO CURFORMAT VALUES (-1, 'INR', 1 , -1, 'R', 2, NULL, NULL);

-- To add currency formatting description
INSERT INTO CURFMTDESC VALUES (-1, -1, 'INR', -1, '₹', NULL, '₹ ',NULL, NULL, '₹ ',NULL, NULL, NULL, '#,##0.00', 'Indian Rupees', NULL);

-- To add currency conversion details. It is an optional step
INSERT INTO CURCONVERT (STOREENT_ID, FROMCURR, TOCURR, FACTOR, MULTIPLYORDIVIDE, BIDIRECTIONAL, UPDATABLE, CURCONVERT_ID) VALUES (-1, 'USD', 'INR', '65.00','M', 'Y', 'Y', -12)

Step 2. Add below entries against each stores (in case of extended sites), where INR should be displayed as one of the currency.

UPDATE STOREENT SET SETCCURR = 'INR' WHERE STOREENT_ID= <store_id>;

INSERT INTO CURLIST VALUES (<store_id>, 'INR', NULL);

UPDATE STORECONF SET VALUE='0' WHERE STOREENT_ID=<store_id> AND NAME='wc.search.priceMode';

* If you do not update the pricemode entry in STORECONF table, the price of the item will get displayed as "price pending".

Instead of performing step 2, we can also associate currency through management center as mentioned below.

a) Logon to management center
b) Select store management option from the top left navigation
c) Select the store in which this change need to be applied
d) Select INR as the default currency. Remove whatever currencies are not required for your site.
e) Click Save and Close


Similar way, any additional currency support can be added in WebSphere Commerce.

If you are using dataload utilities to load price details to WCS, you might need to modify the data load configuration files to support this new currency.

wc-dataload-env.xml:

In the business context configuration, mention currency as 'INR'.

wc-loader-offer.xml:

In config reader section, add an entry to support INR price.

<_config:column number="14" name="PriceInINR"/>

In the datamapping section in BusinessObjectBuilder section, add/update the following entries.

<_config:mapping xpath="PriceEntry[0]/Price/Price/Currency" value="INR" valueFrom="Fixed"/>
<_config:mapping xpath="PriceEntry[0]/Price/Price/value" value="PriceInINR" />



What is XSL and How to generate it

XSL is similar to CSS, it is a language for expressing style of an XML document where as CSS is used to define the style of a web page.

By applying XSL transformation, the style and structure of an existing XML document can be changed. In practical scenario, XML transformation can be applied if the structure of XML generated by one system is not in the format expected by the other system.

Here I am depicting a simple example on how to create an XSL to convert the structure of XML given in the Table-1 to Table-2. 

Table-1 (input file)
<Students>
      <Student>
                 <Name>Prabheesh</Name>
                  <Age>15</Age>
                  <Class>10</Class>
                  <Physics>86</Physics>
                  <Chemistry>85</Chemistry>
                  <Maths>88</Maths>
       </Student>
       <Student>
                 <Name>Vaishnav</Name>
                  <Age>14</Age>
                  <Class>9</Class>
                  <Physics>90</Physics>
                  <Chemistry>92</Chemistry>
                  <Maths>83</Maths>
       </Student>
</Students>
                

Table-2 (output file)
<Students>
      <Student>
                  <PrimaryInformation name=”Prabheesh” age=”15” class=”10”/>
                  <Marks>
                            <physics>86</Physics>
                            <Chemistry>85</Chemistry>
                            <Maths passmark="70">88</Maths>
                   </Marks>
        </Student>
       <Student>
                     <PrimaryInformation name=”Vaishnav” age=”14” class=”9”/>
                  <Marks>
                            <physics>90</Physics>
                            <Chemistry>92</Chemistry>
                            <Maths passmark="70">83</Maths>
                   </Marks>
       </Student>
</Students>
  



First, let us create an XSL file template. If you are using Eclipse/RAD, right click on the project name (assuming project is already existing in your workspace) and choose New -> Other -> XML -> XSL option. Enter a name for the XSL file (eg: mySample.xsl).

This will create an XSL template as below.

<?xml version=”1.0” encoding”UTF-8”?>
<xsl:stylesheet xmlns:xsl=”http://www.w3.org/1999/XSL/Transform” version=”1.0”>


</xsl:stylesheet>


Now, let us see how to create XSL for converting XML document given in Table-1 to the one given in Table-2.

In a high level, the difference between these 2 XML documents are as follows.

a) Name, age and class nodes in the input XML (Table-1) needs to be transformed to attributes of <Primary Information> node.
b) A new node <Marks> is introduced to hold only mark details.
c) An extra attribute "passmark" is added in <Maths> node, whose value is fixed across all the students.


Given below is the XSL code that I developed for this transformation.
 
<?xml version=”1.0” encoding”UTF-8”?>
<xsl:stylesheet xmlns:xsl=”http://www.w3.org/1999/XSL/Transform” version=”1.0”> 

<xsl:variable name=”passmark” select”’70’”/></xsl:variable>

<xsl:template match=”/”>
<Students>
<xsl:for-each select=”Students/Student”>
         <Student>
                  <PrimaryInformation>
                                   <xsl:attribute name=”name”><xsl:value-of select=”Name”/></xsl:attribute>
                                   <xsl:attribute name=”age”><xsl:value-of select=”Age”/></xsl:attribute>
                                   <xsl:attribute name=”class”><xsl:value-of select=”Class”/></xsl:attribute>
                  </PrimaryInformation>

                 <Marks>
                               <Physics><xsl:value-of select=”Physics”/></Physics>
                               <Chemistry><xsl:value-of select=”Chemistry”/></Chemistry>
                              <Maths>
                                           <xsl:attribute name=”passmark”><xsl:value-of select=”$passmark”/></xsl:attribute>
                                             <xsl:value-of select=”Maths”/>
                              </Maths>
                        </Student>
          </xsl:for-each>
 </Students>
</xsl:template>
</xsl:stylesheet>


Now, I will explain the purpose of using each of the xsl elements mentioned above.

xsl:variable:

This is used to define a variable in XSL and assign value to it. Similar to other programming languages, this variable name can be used in the remaining portion of the document display the value assigned to this variable.

In this example, the passmark that need to be displayed against all the students in the XML is 70. Hence in the XSL, we defined it as a variable with value as 70. To display the value of the variable, the following XSL code can be used.

<xsl:value-of select=”$passmark”/>


xsl:for-each:

This construct is used to iterate through the nodes in the XML document. In our example, it will iterate through each <student> node. Whatever code we are writing inside this xsl:for-each logic will be to process the child nodes of <student> node.


xsl:attribute:

This element is used to define an attribute of a node. the name fields refers the name of the node.

xsl:value-of:

This will print the value of the variable or field specified inside the select clause.
<xsl:value-of select=”Name”/> will take the value of "Name" node present inside "Student" node and print it in the output XML. In the example, values "Prabheesh","Vaishnav" are printed using this code.

<xsl:value-of select=”$passmark”/> will print the value of the variable passmark. To print the value of variable, we need to append $ sign in front of the variable name. If the variable is not already defined in the XSL file, the transformation will fail.


To generate the transformed output XML, right click on the XSL we have created (in eclipse/RAD) and select Run As -> XSL Transformation. It will display a pop-up with option to specify input and output XML file. Choose the file with the contents mentioned in Table-1 as input. Mention a new file name as output XML. Click Apply and Run. You can see that an output XML is created with the contents mentioned in Table-2.





Saturday, July 23, 2016

Creating a new Eclipse Project Wizard: Eclipse Plugin development


These are Eclipse customization technique, to add our own projects to the Eclipse plugin.

Project Wizard is the one used to create a new project in Eclipse. All the project that are plugged in with Eclipse will list down at this project Wizard. If you want to create a Java project you can choose ‘Java Project’ and it will load libraries and folder structure for that are requires for that Java project.
Similarly you can create a new your own plugin project (Integration of a new tool to Eclipse, parsing of files etc) and integrate with Eclipse. If you want to add a new our own project in to the Eclipse, the first step to add a new project Wizard.

project Wizard Window:
If you want to create a project, you can go to Eclipse project wizard (File-> New-> Other)


Then the project Wizard Window will be displayed with all the project list that are plugin to that Eclipse version.

If you create a new Eclipse Project Wizard, then that also will list down in the above list.

Steps for creating the new plugin-project in eclipse


First, you need to create new plug-in project by choosing the template as custom plug-in wizard (New File Wizard).

  1. Choose File > New > Project to select a project wizard.
  2. Under Plug-in Development, select Plug-in Project, as shown below.
  3. Click Next to advance to the next step.
  1. Add a project name (TestWizard). Click Next.
  1.  After you have filled in the information as shown below, click Next.
  1. Choose Custom plug-in wizard. Click Next.
  1. In the Template Selection window, click Deselect All to unselect all the options. Then, choose New File Wizard, as shown below. Click Next
  1. The Eclipse wizard prompts you for some information about the new wizard you're creating. Make sure you update the package name, ideally to the same name that you used for the Activator (testwizard). Update the Wizard Category Name to the name of the folder for the new wizard. The Wizard Class Name is a Java class name for the class that inherits from Wizard and implements the INewWizard interface. The Wizard Page Class Name extends the WizardPage class.
  1. Click Finish. Eclipse adds your new project with the necessary classes and libraries.
Folder structure of the wizard project

It will automatically create NewWizard and NewWizardPage and Plugin.xml.

1.      Go to Plugin.xml , extension tab, there you will be able to view the new wizard that we added.

If required, we can change the category name and wizard name here.

New Wizard Class structure



If you click on the class link (class*) it will go to the default class  TestNewWizard’.

(addPages, performFinish, doFinish, openContentStream, throwCoreException,init are the method inside this class)

We can add new pages to the testNewWizard.java

addPages -  The addPages() method adds pages to the wizard.

We can create our own wizard pages or use existing in wizard pages and add that pages to the wizard using the addpage (wizardpage) method.


private WizardNewProjectCreationPage  wizardPage;
public void addPages() {
wizardPage = new WizardNewProjectCreationPage("NewTestProject");
        wizardPage.setDescription("Create a new Test Project.");
        wizardPage.setTitle("New Test Project");
        addPage(wizardPage);
}
Here we want to create project creation wizard, we can use the already existing wizard ‘WizardNewProjectCreationPage’ that is coming with org.eclipse.ui.dialogs package.


Testing the New Wizard



To launch your plug-in project, right-click on the Plugin.xaml, and select Run As > Eclipse Application as shown in below Figure. A new instance of Eclipse starts up.

  1. In that new Eclipse got to the Choose File > New > Others to select a project wizard.
  2. Where you will be able to view the your Wizard Test Wizards(Category name in extension tab of pulgin.xml) and Test Wizard(Wizard name in extension tab of pulgin.xml),   (Note: If you change this name in extension tab it will reflect here)

When you select TestWizard, the ‘Next’ icon will be enabled and you will be able to go to the new project wizard selection page as shown below:

Here you will be able to give name of your new Test Project. Then finish button will be enabled.

FAQ: IIB - instance initializer Block


What is This Block or Instance Initializer Or IIB  ?

This is an anonymous block, without any prefix or modifier, present inside class. It is used to initialize instance data members (instance variables).

2.       When IIB is invoked?

IIB will be invoked for each object creation. i.e for each time when the instance of the class is created.

3.       Which is invoked first IIB or Constructor?

IIB is called first. IIB is invoked before the constructor of the class are invoked.

4.       Order of execution of IIB from subclasses?

When the object of the subclasses are created, super class IIB will invoked first. Subclass Constructor will call super() class constructor first. Like the same way Super class IIB will execute before super class constructor.

Order of execution will be like below during subclass object creation :

Super class IIB à super class constructor --> subclass IIB --> subclass constructor


5.       How compiler will see the code ?

Consider we have below code :

public class ThisIntializer extends ThisSuper {
               
{
                System.out.println("ThisIntializer : Subclass this block 1........");
}

ThisIntializer() {

                System.out.println("ThisIntializer : Subclass Constructor .......");

}

During the compilation compiler will see the code as below:

public class ThisIntializer extends ThisSuper {

ThisIntializer() {

       Super()
{
                System.out.println("ThisIntializer : Subclass this block 1........"); 
   }

        System.out.println("ThisIntializer : Subclass Constructor .......");

}


6.       What is the use of IIB?  And where it is used?

IIB is using mainly for initializing instance data member (instance variable – non static variables). IIB is doing the same as what constructor is doing.
But we used the same in some places where we want to do below activities:

·         If you want to do some operation before assigning values to instance data members (instance variables). Like array, List initialization or for doing complex calculation.
·         For doing error handling by catching exceptions and using finally.
·         As a initializer for anonymous inner classes.(we can’t declare any constructor inside the  anonymous inner classes).

7.       If Constructor is able to do the initialization of instance variable, why we need IIB ?

The assigning and error handling that is mentioned in above (6th question) will be able to achieve with constructor also, but if the class is having more than one constructor, we would have to repeat this code in each constructor. At this point of time IIB will be good to use.
It is mainly useful in the case of anonymous inner classes, where the is no constructor available for initialization of variables.

Example for anonymous inner classes using he  IIB ?
……………………………..
                                                new Thread(new Runnable(){
                                                                Path file = Paths.get("./test.txt");
                                                                {                                                              
                                                                                try{
                                                                                InputStream in = Files.newInputStream(file);
                                                                                    BufferedReader reader =
                                                                                  new BufferedReader(new InputStreamReader(in));
                                                                                 String line = null;
                                                                                 while ((line = reader.readLine()) != null) {
                                                                                      System.out.println(line);
                                                                                    }
                                                                                } catch (IOException x) {
                                                                    System.err.println(x);
                                                                                }
                                                                }
                                                                @Override
                                                                public void run() {
                                                                                System.out.println("run ");
                                                                               
                                                                }

                                                  
                                                }).start();
                               
………………………….

Example for exception handling from IIB ? Can IIB threw a checked exception?
We can handle exception from IIB. But only thing is that if we are throwing any checked exception from IIB , then that should be declared by the constructors.

E.g
public class innerClass {
                StringReader reader = null;
    {
                reader = new StringReader(new String("test"));
        try {
                reader.read();
                                } catch (IOException e) {
                                throw e;
                                               
                                }
    }
    innerClass() throws IOException {
               
    }

In the above code if we don’t throw an Exception from constructor then the code will not compile.

 Example for Exception handling from IIB , for anonymous inner classes ?

    Instance initializers in anonymous inner classes can throw any exception. See the question number 8.


This block - Instance Initializer Block – (IIB) - instance initializers

This block, also known as instance initializer block is used for initializing instance data member (instance variable – non static variables).
This block will execute each time for each object creation for the class. This is invoked before the constructor of the class are invoked.
Example :
public class ThisIntializer extends ThisSuper {
               
{
                System.out.println("ThisIntializer : Subclass this block 1........");
}

ThisIntializer() {

                System.out.println("ThisIntializer : Subclass Constructor .......");

}
{
System.out.println("ThisIntializer : Subclass this block 2........");
}
public static void main(String[] args) {
                               
System.out.println("--------- Creating first Object o1 ----------");

                                ThisIntializer o1 = new ThisIntializer();

System.out.println("--------- Creating first Object o2 --------------");

                                ThisIntializer o2 = new ThisIntializer();
}

}

class ThisSuper {
                {
                System.out.println("ThisSuper : Super class This Block ....");
                }
                ThisSuper () {

                System.out.println("ThisSuper : Super Class constructor ......");

                }
}

---------------------------Output -------------------------------------------

--------- Creating first Object o1 ----------
ThisSuper : Super class This Block ....
ThisSuper : Super Class constructor ......
ThisIntializer : Subclass this block 1........
ThisIntializer : Subclass this block 2........
ThisIntializer : Subclass Constructor .......

--------- Creating first Object o2 --------------
ThisSuper : Super class This Block ....
ThisSuper : Super Class constructor ......
ThisIntializer : Subclass this block 1........
ThisIntializer : Subclass this block 2........
ThisIntializer : Subclass Constructor .......

-----------------------------End of Output-----------------------------------

Things to Know:

1.       instance initializer will call for Each Object creation (i.e each time when the instance of the class is created)
2.       Like Constructor, for instance initializer also super class instance initializer will execute first.
ie. Super class this block à super constructor --> subclass this block --> subclass constructor
3.       The java compiler copies the code of instance initializer block in every constructor.
For compiler code for ThisIntializer constructor will be look as below :
ThisIntializer() {

       Super()
{
                System.out.println("ThisIntializer : Subclass this block 1........"); 
   }

        System.out.println("ThisIntializer : Subclass Constructor .......");

}

4.       If 1 or more this block present in the program then the order for executing this block will be , the order in which they appears in the program.
5.       We can’t return anything from ‘instance initializer’. i.e ‘return’ are not allowed inside instance initializer.
But we can throw a checked exception from instance initializer ( only if the checked exceptions are explicitly declared in the throws clause of every constructor in the class).


------------------------------------------------------------------------------------------------------------------------------------------


Where to use and why?

1.       If you want to do some operation before assigning values to instance data members (instance variables). Like array, List initialization or for doing complex calculation.
2.       For doing error handling by catching exceptions and using finally.

The above two scenario we will be able to do in constructor also, but if the class is having more than one constructor, we would have to repeat this code in each constructor.

3.       As a initializer for anonymous inner classes.(we can’t declare any constructor inside the  anonymous inner classes). Instance initializers in anonymous inner classes can throw any exception.


The below Code is having compilation Error:

public class innerClass {
                StringReader reader = null;
    {
                reader = new StringReader(new String("test"));
        try {
                reader.read();
                                } catch (IOException e) {
                                throw e; // compilation error
                                               
                                }
    }
    innerClass() {
               
    }
               
public static void main(String[] args) throws IOException {
innerClass i = new innerClass();

}

Corrected Code :

public class innerClass {
                StringReader reader = null;
    {
                reader = new StringReader(new String("test"));
        try {
                reader.read();
                                } catch (IOException e) {
                                throw e;                                               
                                }
    }
    innerClass() throws IOException {
               
    }
                /**
                 * @param args
                 * @throws IOException
                 */
                public static void main(String[] args) throws IOException {
                                innerClass i = new innerClass();
}



Example for anonymous inner classes

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class innerClass {
                StringReader reader = null;
    {
                reader = new StringReader(new String("test"));
        try {
                reader.read();
                                } catch (IOException e) {
                                throw e;
                                               
                                }
    }
    innerClass() throws IOException {
               
    }
                /**
                 * @param args
                 * @throws IOException
                 */
                public static void main(String[] args) throws IOException {
                                innerClass i = new innerClass();
                                // TODO Auto-generated method stub
                                                new Thread(new Runnable(){
                                                                Path file = Paths.get("./test.txt");
                                                                {                                                              
                                                                                try{
                                                                                InputStream in = Files.newInputStream(file);
                                                                    BufferedReader reader =
                                                                      new BufferedReader(new InputStreamReader(in));
                                                                    String line = null;
                                                                    while ((line = reader.readLine()) != null) {
                                                                        System.out.println(line);
                                                                    }
                                                                } catch (IOException x) {
                                                                    System.err.println(x);
                                                                }
                                                                }
                                                                @Override
                                                                public void run() {
                                                                                System.out.println("run ");
                                                                               
                                                                }

                                                  
                                                }).start();
                               
                }

}

For more FAQ on instance initializer block, please refer  IIB FAQ