Friday, October 30, 2015

Solution for larger numbers which get read in exponential format from excel.

When you try to read excel in JAVA and come across cells which have Numbers greater than 12 digits, it will automatically get converted in Exponential format.

Example: 104009000084 gets converted to 1.04009000084E11

Now even if you change the cell format from Number to Text, it still considers it as Number and converts it to exponential format while reading the file in JAVA.

Solution 1:
Write sign ' before the number in excel sheet.

Solution 2:
Delete the value from excel , change the format from Number to Text and then rewrite the value back to excel.




Tuesday, October 27, 2015

POI API for writing data from excel file to a text file.

Many times you will come across situations, wherein you will need to read data from excel files and do some processing.

POI API comes to the rescue here :)

Download the latest POI jar file and add it to your project library.

import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

public class ConvertFile 
{
   public static void main(String[] args) 
   {
      System.out.println("Start of Program");
      try
      {
FileInputStream file = new FileInputStream(new File("D:\\Test_Data_Automation.xls"));

//Get the workbook instance for XLS file 
HSSFWorkbook workbook = new HSSFWorkbook(file);

//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(2);

//Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();

String fileName = "";
PrintWriter writer = null;

        while(rowIterator.hasNext())
         {
            Row row = rowIterator.next();
       
            //For each row, iterate through each columns
            Iterator<Cell> cellIterator = row.cellIterator();
             
            try{
                 writer = new PrintWriter("D:\\Output_Data.txt", "UTF-8");
            }catch(Exception ex){ex.printStackTrace();}
                          
            while(cellIterator.hasNext()) 
            {
               Cell cell = cellIterator.next();
                       
            if(cell.getRowIndex() > 3)      //Start reading from the 3rd row.
            {
               switch(cell.getCellType()) 
               {
                  case Cell.CELL_TYPE_BOOLEAN:
                  System.out.print(cell.getBooleanCellValue() + "\t\t");
                  writer.println(String.valueOf(cell.getBooleanCellValue()));
                  break;
                  
                   case Cell.CELL_TYPE_NUMERIC:
                  System.out.print(cell.getNumericCellValue() + "\t\t");
                  writer.println(String.valueOf(cell.getNumericCellValue()));
                  break;
                   
                   case Cell.CELL_TYPE_STRING:
                  System.out.print(cell.getStringCellValue() + "\t\t");
                  writer.println(String.valueOf(cell.getStringCellValue()));
                  break;
                   
                   case Cell.CELL_TYPE_FORMULA:
                  cellValue=String.valueOf(cell.getStringCellValue());
                  break;
                   
                   case Cell.CELL_TYPE_ERROR:
                  cellValue=String.valueOf(cell.getStringCellValue());
                  break;
                  }
            }
             }
             
             try{
             System.out.println("Close the file");
                 writer.close();
             }catch(Exception ex){ex.printStackTrace();}
         }

         System.out.println("End of Program");

     }
     catch(Exception ex) {ex.printStackTrace();}
   }
}   //End of Main


Some Important syntax->
1) To read any row apart from the current row, use the following.
     Row nextRow = sheet.getRow(row.getRowNum() + 1);
     Row prevRow = sheet.getRow(row.getRowNum() - 1);
     Row next2Row = sheet.getRow(row.getRowNum() + 2);
     Row prev2Row = sheet.getRow(row.getRowNum() - 2);
     etc.

2) To read any column in any particular row, use the following.
     row.getCell(1);
     row.getCell(7);
     row.getCell(11);
     etc.

Tuesday, October 6, 2015

How to check EPF (Employee Provident Fund) balance

How much money goes in the PF (Provident Fund) Account?
  1. Employee Contribution : 12% of your Basic
  2. Employer Contribution  : 12%  of your Basic (8.33% goes to EPS)
  3. Interest on both the contribution.

What is EPS?

EPF = Employee Pension Scheme.

The purpose of the scheme is to provide for
1) Superannuation Pension:Member who has rendered eligible service of 20 years and retires on attaining the age of 58 years.
2) Retiring Pension:member who has rendered eligible service of 20 years and retires or otherwise ceases to be in employment before attaining the age of 58 years.
3) Permanent Total Disablement Pension 4) Short service Pension: Member has to render eligible service of 10 years and more but less than 20 years.



Steps to check PF Online:

1) Get your PF Account Number - It is normally mentioned on your payslip, if not check with your HR team.

It will look like MH / 98765 / 1234567

2) Go to EPFO website - http://epfindia.com/site_en/KYEPFB.php

3) Click on the following link -> "Click here to know Your PF Balance"




4) Select your State and Office Name as shown below.




5) Enter all the details as shown below and click on "Submit" Button.

First 2 text fields will be populated automatically.

You can keep the 4th text blank, if you dont know the extension number.




6) You will now receive an SMS from EPFO.

In the SMS, 2 amounts will be mentioned "EE Amount" and "ER Amount".

EE Amt = Employee Balance

ER Amt = Employer Balance
 

Monday, September 14, 2015

Change logo on the header section (Left Corner)

Logo on hybris gets diaplayed on the header in the left corner with the following tag in header.tag file.

<cms:component component="${logo}" class="siteLogo" element="div"/> 

But this logo comes from the database.

Hence if you want to change the logo, you need to use the below impex scripts.

INSERT_UPDATE Media;$contentCV[unique=true];code[unique=true];realfilename;@media[translator=de.hybris.platform.impex.jalo.media.MediaDataTranslator];mime[default='image/jpeg'];folder(qualifier)[default='images'];altText ;;/images/theme/logo-hybris.png;logo-hybris.png;$siteResource/images/theme/logo-hybris.png;image/png;;"hybris Accelerator"

UPDATE SimpleBannerComponent;$contentCV[unique=true];uid[unique=true];$picture[lang=$lang] ;;SiteLogoComponent;/images/theme/logo-hybris.png


Finally restart the server :)

Difference bet ContentSlotName, ContentSlot, ContentSlotForTemplate & ContentSlotForPage

What is the difference between ContentSlotName, ContentSlot, ContentSlotForTemplate and ContentSlotForPage?
 
 
Content Slots hold WCMS Components
 
 
Content Slot for Templates are default slots when not overriden at page level (i.e. top-nav, header, footer)
 
 
Content Slot for Page are slots assigned to an individual page instance and override the template level slot (i.e. homepage, sony brand landing page)
 
 
Content Slot Name is a logical tagging for a content slot (aka Navigation Section, Top Merchandizing, Footer, Product Image Slot). To the Content Slot Name you can configure the types of components that will work in a slot.

Wednesday, September 2, 2015

Webservices in Hybris

Hybris provides a great way to expose all of its functionality via webservices, We can provide all the data available in the hybris database (products, promotions, vouchers , wishlist etc) to third party applications which are not built using Hybris.

Some webservices are exposed via http and 9001 port where-as others where spring-security is applied are exposed via https and 9002 port.

Accessing normal webservices is pretty straight forward. But there is a way to access webservices where spring-security is applied.

Most of the features are provided by Hybris Out-Of-The-Box (OOTB).
In case of customization we only have to Fetch data either by Flexible Search Query or from services, add them to a list and return the list to the calling application. 

Rest of the things will be taken care by Hybris automatically :)  

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


Follow these steps to make your own custom extension for webservices ->
1) Go to platform directory of hybris and type the modulegen command.

Hybris5.4\hybris\bin\platform> ant modulegen
 
2) You will be provided the following templates to select.

[input] Press [Enter] to use the default value ([accelerator], b2baccelerator, telcoaccelerator, commercewebservices)

Select commercewebservices

3) You will be asked to name your extension.

Press [Enter] to use the default value [training]

Example Name -> myWebService
 
4) You will be asked to enter package name.

Press [Enter] to use the default value [org.training]

Example Package -> org.webservice

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


Add the following entries to localextensions.xml file ->
<path dir="${HYBRIS_BIN_DIR}" />
<!-- ext-platform -->
<extension name="admincockpit" />
<extension name="backoffice" />
<extension name="cockpit" />
<extension name="hmc" />
<extension name="mcc" />
<extension name="platformhmc" />
<!-- ext-commerce -->
<extension name="btg" />
<extension name="btgcockpit" />
<extension name="commercesearch" />
<extension name="commercesearchbackoffice" />
<extension name="commercesearchhmc" />
<extension name="commerceservices" />
<extension name="basecommerce" />
<extension name="payment" />
<extension name="promotions" />
<extension name="voucher" />
<extension name="customerreview" />
<extension name="ticketsystem" />
<extension name="solrfacetsearch" />
<extension name="solrfacetsearchhmc" />
<extension name="oci" />
<extension name="wishlist" />
<extension name="commercefacades" />
<!-- ext-data -->
<extension name="commercesearchsampledata" />
<extension name="apparelstore" />
<extension name="electronicsstore" />
<extension name="instoresampledata" />
<!-- ext-content -->
<extension name="productcockpit" />
<extension name="cms2" />
<extension name="cms2lib" />
<extension name="cmscockpit" />
<extension name="bmecat" />
<extension name="bmecathmc" />
<extension name="importcockpit" />
<extension name="classificationsystems" />
<extension name="classificationsystemshmc" />
<!-- ext-channel -->
<extension name="cscockpit" />
<extension name="mobileoptionals" />
<extension name="mobileservices" />
<extension name="instore" />
<!-- ext-addon -->
<extension name="addonsupport" />
<!-- ext-print -->
<extension name="print" />
<extension name="printcockpit" />
<extension name="printhmc" />
<!-- ext-accelerator -->
<extension name="acceleratorservices" />
<extension name="acceleratorfacades" />
<extension name="acceleratorcms" />
<extension name="acceleratorstorefrontcommons" />
<!-- custom-webstore -->
<extension name="myWebStorecockpits" />
<extension name="myWebStorecore" />
<extension name="myWebStorefacades" />
<extension name="myWebStorefulfilmentprocess" />
<extension name="myWebStoreinitialdata" />
<extension name="myWebStorestorefront" />
<extension name="myWebStoretest" />
<!-- custom-sebservice -->
<extension name="myWebService" />





Note : In some versions of Hybris, you make have to include one more extension -> <extension name="platformwebservices" />
 
------------------------------------------------------------------------------------------------------------------------


Go to extensioninfo.xml file of the newly created extension -> myWebService.

You will see the following entries->
<extension abstractclassprefix="Generated" classprefix="Ycommercewebservices" name="myWebService" usemaven="false">
<requires-extension name="commercefacades"/>
<requires-extension name="commerceservices"/>
<requires-extension name="commercewebservicescommons"/>
<coremodule generated="true" manager="de.hybris.platform.jalo.extension.GenericManager" packageroot="org.webservice.core"/>
<webmodule jspcompile="false" webroot="/myWebService"/>
<meta key="extgen-template-extension" value="true"/>
</extension>


Here this line is very important  ->

<webmodule jspcompile="false" webroot="/myWebService"/>.

You will be calling your webservices with the root as /myWebService. Here you can give any name you want to give but you need to use the same name mentioned in this file for calling your webservices.


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


Time to check the webservice.
Build the code and start hybrisserver.

Now open Rest-Client and execute the following webservice request to fetch product details from Hybris.

URL - http://localhost:9001/myWebService/v1/electronics/products

Method : GET

You can view the response in the body of rest client as shown below.







Now if you try to make this call - https://localhost:9002/myWebService/v1/electronics/customers/current

You will get the following error.



It is because this call has been secured and requires authentication.

Steps for Authentication :
Type the following URL in RestClient.

http://localhost:9001/myWebService/oauth/token?client_id=mobile_android&client_secret=secret&grant_type=password&username=hrishikesh.maluskar@igate.com&password=Aug@2015

Method = POST


Output =



Note: You need to be a registered user, else it will give "Bad Credentials" error.
 
 
Authorization entries are present in security-spring.xml located at the following location.  
myWebService/web/webroot/WEB-INF/config/security-spring.xml<oauth:client-details-service id="clientDetails">
<oauth:client client-id="client-side" resource-ids="hybris" authorized-grant-types="implicit,client_credentials"
authorities="ROLE_CLIENT" secret="secret" redirect-uri="
http://localhost:8080/oauth2_implicit_callback" />
<oauth:client client-id="mobile_android" resource-ids="hybris"
authorized-grant-types="authorization_code,refresh_token,password,client_credentials" authorities="ROLE_CLIENT" secret="secret"
redirect-uri="
http://localhost:8080/oauth2_callback" />
<oauth:client client-id="trusted_client" resource-ids="hybris"
authorized-grant-types="authorization_code,refresh_token,password,client_credentials" authorities=" ROLE_TRUSTED_CLIENT”
secret="secret" /> </oauth:client-details-service>



Now add the access token in the header of Rest-Client as shown below.
 
 
From now onwards whenever you make any webservice calls, you will no longer be an anonymous user but will be logged in with the user-id of whom the credentials were provided while acquiring the access_token above.

Now again if you try to make this call -
https://localhost:9002/myWebService/v1/electronics/customers/current

You will still get the following error.
 
 

To solve this go to SSL tab of Rest-Client

 

Here enter the following->
 
Trust store file : Select keystore file located at the following path of your Hybris Commerce Suite.
Path = \hybris-commerce-suite-5.4.0.3\hybris\bin\platform\tomcat\lib\keystore
 
Trust store password : 123456
 
Hostname verifier : Allow All
 
Now if you try to make this call -https://localhost:9002/myWebService/v1/electronics/customers/current


You will get the following output ->
 

 
 
If you observe there was no need to pass customerID, from the access_token it automatically passes the customerID.

Note : If you want to use this logic from JAVA code, then you have to write code to append access_token in the header of request.
 

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


By default Hybris provides various webservice calls, related to various functionalities which are located in the following files->
 
 
 
If you want to expose something which is not provided in the above files then you need to do further customization.

Steps:

1) Create your own class and extend it from the BaseController

@Controller("wishlistControllerV1")
@RequestMapping(value = "/{baseSiteId}/wishlist")
public class WishlistController extends BaseController
 

2) Write your own method, fetch the required data, add it to a list and return the list.

@RequestMapping(value = "/getDefaultWishlist", method = RequestMethod.GET)
@ResponseBody
public List<WishlistData> getDefaultWishlist() throws Exception
{
final List<WishlistData> listFinal = new ArrayList<WishlistData>();
final Wishlist2Model wishlist2Model = wishlistService.getDefaultWishlist(userService.getCurrentUser());
final List<Wishlist2EntryModel> list = wishlist2Model.getEntries();
final Iterator iterator = list.iterator();
while (iterator.hasNext())
{
Wishlist2EntryModel productModel = new Wishlist2EntryModel();
productModel = (Wishlist2EntryModel) iterator.next();
final WishlistData wishlistData = new WishlistData();
wishlistData.setCode(productModel.getProduct().getCode());
wishlistData.setName(productModel.getProduct().getName());
wishlistData.setPriceQuantity(productModel.getProduct().getPriceQuantity());
wishlistData.setPriority(String.valueOf(productModel.getPriority()));
wishlistData.setAddedDate(productModel.getAddedDate());
listFinal.add(wishlistData);
}
}
return listFinal;
}


3) If the data is not accessible via available services then you can write Flexible Search Query.  
final FlexibleSearchQuery query = new FlexibleSearchQuery("select {pk} from {voucher}");
Add this result to a list and return the list.  

Note:
If you don’t want to customize webservice and use the default webservices provided use /rest instead of your custom name /myWebService.

Example :
 
Custom : http://localhost:9001/myWebService/v1/electronics/cart  
Default : http://localhost:9001/rest/v1/electronics/cart
 

That’s all for Hybris-webservices :)
 

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


Some sample webservice calls provided by Hybris OOTB.

Authenticaiton
http://localhost:9001/myWebService/oauth/token?client_id=mobile_android&client_secret=secret&grant_type=password&username=hrishikesh.maluskar@igate.com&password=Aug@2015

Get the current logged in user https://localhost:9002/myWebService/v1/electronics/customers/current
 
Get the current session cart

http://localhost:9001/myWebService/v1/electronics/cart
 
Add to cart

http://localhost:9001/myWebService/v1/electronics/cart/entry?code=107701&qty=2
 
Logout current user http://localhost:9001/myWebService/v1/electronics/customers/current/logout
 
Promotions list

https://localhost:9002/myWebService/v1/electronics/promotions?type=all
(type can be all,order,product)
 
Product list

https://localhost:9002/myWebService/v1/electronics/products

Get Voucher Information

https://localhost:9002/myWebService/v1/electronics/vouchers/999-965M-4Y95-34GY
 
Apply voucher to cart

https://localhost:9002/myWebService/v1/electronics/cart/voucher/999-965M-4Y95-34GY

Release voucher from cart
https://localhost:9002/myWebService/v1/electronics/vouchers/999-965M-4Y95-34GY
















Thursday, August 27, 2015

Garbage Collection in JAVA

1) When the garbage collector runs, its purpose is to find and delete objects that cannot be reached.
 
2) The garbage collector is under the control of the JVM. The JVM decides when to run the garbage 
     collector.
 
3) An object is eligible for garbage collection when no live thread can access it.
 
4) Garbage collection cannot ensure that there is enough memory, only that the memory that is
    available will be managed as efficiently as possible.
 
5) The simplest way to ask (request) for garbage collection in System.gc();
 
6) About the only thing you can guarantee is that if you are running very low on memory, the garbage
    collector will run before it throws an OutOfMemoryException.
 
7) JAVA provides you a mechanism to run some code just before your object is deleted by the
    garbage collector. This code is located in a method named finalize() that all classes inherit from
    class Object.
    - For any given object, finalize() will be called only once (at most) by the garbage collector.
    - Calling finalize() can actually result in saving an object from deletion.
 
    For example, in the finalize() method you could write code that passes a reference to the object in
    question back to another object, effectively uneligibilizing the object for garbage colleciton.
 

Wednesday, August 26, 2015

Adding a column to a table in Hybris database

What will you do if you want to add a new column to a table in Hybris database?

Let us take an example of customerReview Table.

If you run the following query in Hybris console , you will get the default columns already available -


 
Now if you wish to add a new column say STANDING to this CUSTOMERREVIEW table, do the following -

1) Add the following code to commercefacades-beans.xml available in commercefacades extension, note here standing property of type string has been added to the already existing code.

<bean class="de.hybris.platform.commercefacades.product.data.ReviewData">
<property name="id" type="String"/>
<property name="headline" type="String"/>
<property name="comment" type="String"/>
<property name="rating" type="Double"/>
<property name="date" type="java.util.Date"/>
<property name="alias" type="String"/>
<property name="standing" type="String"/>
<property name="principal" type="de.hybris.platform.commercefacades.user.data.PrincipalData"/>
</bean>
 
 
2) Add the following code to customerreview-items.xml, available in customerreview extension. 

<attribute type="java.lang.String" qualifier="standing">
<description>
Standing will be decided based upon the no of reviews.
</description>
<modifiers initial="true" optional="false" />
<persistence type="property" />
</attribute>


3) Run Ant Clean All and start the hybris server.


4) After this all the Data and Model files related to the newly added property (standing) will be created automatically, you can verify this by opening the following files -> CustomerReviewModel and ReviewData.


5) Go to Admin Console -> Platform -> Update and click on Update Button.




6) Now if you again run the select query, you will find the newly added column :)




In this way you can modify the tables and include your own columns if you want to implement some customized logic.

You can also experiment and add a completely new table to the database.

Monday, August 17, 2015

Memory management in JAVA

Sometimes when you run some java applications you may run out of memory and get exceptions related to memory.

Following code helps you to manage the memory better. Also you may trigger an email to the users or dvelopment team whenever you anticipate shortage of space, so that the development team can take necessary action.

public class MemoryUsage
{

  public static void main(final String[] args)
  {
   final int mb = 1024 * 1024;

   final Runtime runIns = Runtime.getRuntime();
   
   System.out.println("Total Memory = " + runIns.totalMemory() / mb + " mb");
  
   System.out.println("Free Memory = " + runIns.freeMemory() / mb + " mb");
   
   System.out.println("Used Memory = " + (runIns.totalMemory() - runIns.freeMemory()) / mb + " mb");
  
   System.out.println("Max Memory= " + runIns.maxMemory() / mb + " mb");
  }

}

Sunday, August 16, 2015

Move zeroes (0's) to the end of array list

In a arraylist if you have zeroes (0's) at any randon location and want to move all the zeroes to the end of the list keeping the sequence of the list as-is, here is the solution -

Input - 1 9 8 4 0 0 2 7 0 6 0 9

Output - 1 9 8 4 2 7 6 9 0 0 0 0

void puchEnd()
{
   int count = 0;

   //Traverse the list and if element is non-zero, write to the list.
   for(int i=0 ; i<arr.length; i++)
  {
      if(arr[i].equals("0"))
      {
          //do nothing
      }
      else
      {
          arr[count++] = arr[i]; 
      }
  }
  
   //After writing all non-zero elements, now copy zero till the end of list.
   while(count < n)
   {
      arr[count++] = arr[i];
   }
}

JDBC Steps

1) Load the driver class.
    Class.forName("oracle.jdbc.driver.OracleDriver");


2) Create the connection Object.
    Connection con = DriverManager.getConnection  
    ("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");


3) Create the statement Object.
     Statement stmt = con.createStatement();


4) Execute query.
     ResultSet rs = stmt.executeQuery("select * from emp");
     
     while (rs.next)
     {
        System.out.println(rs.getString());
     }


5) Close the conneciton Object.
     con.close();

Wednesday, August 12, 2015

Steps to setup Hybris for the first time

1) Download the latest version of hybris from wiki-hybris.

2) Unzip the hybris multi-channel suite.

3) After unzipping the files, open command prompt and go to this path - hybrisfolder > bin >    
    platform.

4) First we need to set-up ant, so type the following command - setantenv.bat

5) Now build your hybris suite - ant clean all

6) After successful build config folder will be created in your installed hybris directory where it  
     contains 2 important files - local.properties and localextensions.xml

7) Now start the hybris server - hybrisserver.bat

 8) Now type http://localhost:9001/ in the browser.

 9) You now have to click on initialize available under platform > initialization tab, this will
     automatically create all the data required to launch a  ecommerce website as well as the hybris
     management console (hMC) from where you can  control the  data displayed on the website.



10) It takes around 2 hours to complete the initialization process.

11) Now type http://localhost:9001/yacceleratorstorefront?site=electronics in the browser.

12) Ecommerce website will open-up as shown below.


13) This is the default ecommerce website which comes out-of-the box in hybris.

14) You can now mould this website as per the client requirements.

15) Hybris creates 1 more site by default, you can access this by typing
      http://localhost:9001/yacceleratorstorefront?site=apparel in the browser.

16) To open hMC type http://localhost:9001/hmc in the browser.


17) Type username / password as admin / nimda.

18) Hybris Management Console (hMC) will open up, where you can control the data (products,
       price, available quantity etc) displayed on the website.



 

How to Import / Build Hybris in Eclipse

1) Suppose you want to work on ycommercewebservices.

2) Import ycommercewebservices , platform and config folders in eclipse.

3) Now open the extensioninfo.xml file of ycommercewebservices as shown below.


4) Import all the extensions in eclipse which are shown in "requires-extension" attribute as shown below.



5) Repeat step 3 and step 4 for the newly added extensions, till all dependencies are resolved.

6) You will have the following extensions in eclipse at the end. 



7) Build the code in eclipse (Project -> Clean).

8) If you get any maven related errors, comment the following lines in maventasks.xml file.


9) Build the code again, you will get build successful message.

10) All the Data and Model files will be generated in platform/bootstrap folder.


 

Monday, August 10, 2015

Why do we need Design Patterns

You can exploit the wisdom and lessons learned by other developers who have been down the same design problem road and survived the trip.

Instead of code reuse, with patterns you get experience reuse.

Design Patterns give you a shared vocabulory with other developers. Once you have got the vocabulory you can more easily communicate with other developers.

Patters allow you to say more with less.

Design Patterns help you to think - how to create flexible designs that are maintainable and that can cope with change.

You need to know about atleast the following Design Patterns other than MVC :)
  1. Strategy
  2. Observer
  3. Adapter
  4. Facade
  5. Factory
  6. Template
  7. Singleton
  8. Proxy
  9. Decorator
  10. Builder

Friday, August 7, 2015

Authentication and Cart Functionality in Hybris via Webservices

Imagine a scenario when you want a third party application to be in sync with your Hybris application (this may also be a mobile app).

Products ordered in one application should also be visible in the second application.

This scenario can be easily achieved by using webservices which are provided by Hybris OOTB (Out-Of-The-Box).


Steps->

1) If we login to the webportal for the first time, we can see that the cart is empty.



2)      Now logout from the portal.

3)      Now we can add products to the cart by using the below web-services.

4)      //webservice for authentication
http://localhost:9001/rest/oauth/token?client_id=mobile_android&client_secret=secret&grant_type=password&username=hrishikesh.maluskar@igate.com&password=Aug@2015

After you run the above webservice, you get the following output ->
{
  "access_token": "7bd2b9a2-24d6-4939-9c8f-d98b4e464b6a",
  "token_type": "bearer",
  "refresh_token": "efaf6ed2-746e-4263-93dd-f37e485ded7f",
  "expires_in": 17571
}

You need to add this token in the header of RestClient as shown below.


5)      //get the current logged in user
https://localhost:9002/rest/v1/electronics/customers/current

6)      //get the current session cart
http://localhost:9001/rest/v1/electronics/cart

7)      //add to cart
http://localhost:9001/rest/v1/electronics/cart/entry?code=107701&qty=2

8)      //logout current user
http://localhost:9001/rest/v1/electronics/customers/current/logout

9)      Now if you go to the webstore, you will see the product gets added to the cart as shown below.





 

Note: You can also add the header in your JAVA code as shown below.

WebResource webResource = client.resource(your-webservice);
webResource.header("Authorization", "bearer 7bd2b9a2-24d6-4939-9c8f-d98b4e464b6a")



Home