Sunday, November 6, 2016

ArrayList vs Vector



ArrayList
Vector
ArrayList & Vector
Maintains the insertion order of element
Maintains the insertion order of element
Both are ordered collection classes as they maintain the elements insertion order.
ArrayList is not Synchronized.

We can make this Synchronized.
[Collections.synchronizedList(new ArrayList());]
Vector is Synchronized.
ArrayList  is not thread-safe

Vector is Thread-safe, shared between multiple threads.
Faster than Vector.
Give Better performance than Vector.
Better for non-threaded applications.
Much Slower than ArryaList for single thread use.
(Synchronization makes Vector slow)


ArrayList and Vector allows null and duplicates.
ArrayList is using Iterator for Traversing.
Iterator in the ArrayList is fail-fast iterator.
Vector is using both Iterator and Enumerator for Traversing.

Enumerator in the Vector is not fail-fast.
Both Iterator and ListIterator returned by ArrayList and Vector are fail_fast
ArrayList grow by half of its size when resized.
It increase its array size by 50% while insertion.
Vector doubles the size of its array size.
Vector increments 100% if it exceeds its capacity.

Both use dynamically resizable array as a data structure internally
They both can grow and shrink dynamically .(increase or decrease size) when overflow and deletion happens

Doesn’t define increment size.
Default size is 10. (If you create an arraylist means , you had created array with 10 elements and with values for all as null)


It is better to set initial capacity if you know the size in advance.

ArrayList<?> list = new ArrayList<>(20);
 So that we can avoid the cost of resizing.(otherwise if it cross size 10,it will create a new array and copy the data of old to new and , GC the old one)
We can set increment size for vector.
public synchronized void setSize(int i) {}
If you don’t know initial capacity , but if u know the rate at which array can grow use vector.

Introduced in java version 1.2(with collections).
Not a Legacy Class
Introduced in first Versions of Java.
As part of Legacy Classes (older version of java, not used by any one)




Difference between Collection and Collections


collection
collections
Collection & collections
Interface
Root interface for java collection Framework(all the collection interface (List,Set,Queue) are sub interface of it.
Class
Class is a member of Java collection framework.
Interfaces and its implementations classes together form collection framework.
Map interface, doesn’t inherit from Collection interface
Member of java.util package.
Contains abstract methods.

public interface Collection<E>
extends Iterable<E>

Utility class of java.util package.
Contains static method to operate on object of type collection.
public class Collections extends Object
Both are from java.util package.
ArrayList is a class that , implements List interface(sub interface of Collection Interfae)
e.g.
ArrayList<Integer> arrList = new ArrayList<Integer>()
Collections class provide static utility methdos to operate on the object of ArryaList.
e.g. Collections.sort(arrList)

Collection ß  Set,List,Queue

Set ß SortedSetß NavigableSet
Queueß Deque
public class Collections extends Object
Contains methods to perform basic operations.

int size()
boolean isEmpty()               
boolean contains(Object o)                
Iterator<E> iterator()            
Object[] toArray()  
<T> T[] toArray(T[] a)           
boolean add(E e)
boolean remove(Object o)
boolean containsAll(Collection<?> c)
boolean addAll(Collection<? extends E> c)
boolean removeAll(Collection<?> c)             
boolean retainAll(Collection<?> c)                
void clear()            
boolean equals(Object o)
int hashCode()
Stream<E> stream() -> java 8 and later
Stream<E> parallelStream()->java 8 and later

iterator is the only one inherited form Iterator interface.

Some methods from Collections class, to perform operation on collection object.

Collections.max()               
Collections.min()
Collections.sort()
Collections.shuffle()
Collections.synchronizedCollection()               
Collections.binarySearch()               
Collections.disjoint()          
Collections.copy()              
Collections.reverse()

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