Subversion Repositories SmartDukaan

Rev

Rev 13862 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020;

import in.shop2020.model.v1.catalog.CatalogService;
import in.shop2020.model.v1.catalog.Item;
import in.shop2020.model.v1.catalog.SnapdealItem;
import in.shop2020.model.v1.catalog.SnapdealItemDetails;
import in.shop2020.model.v1.catalog.status;
import in.shop2020.model.v1.inventory.InventoryService.Client;
import in.shop2020.model.v1.inventory.InventoryType;
import in.shop2020.model.v1.inventory.ItemInventory;
import in.shop2020.model.v1.inventory.SnapdealInventoryItem;
import in.shop2020.model.v1.inventory.Warehouse;
import in.shop2020.model.v1.inventory.WarehouseLocation;
import in.shop2020.model.v1.inventory.WarehouseType;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.InventoryClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.utils.GmailUtils;
import inventory.Inventory;
import inventory.InventoryHistory;
import inventory.InventoryHistoryItems;
import inventory.InventoryItems;
import inventory.PendingOrderInventoryHistory;
import inventory.SnapdealItemForInventory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.mail.MessagingException;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;

import com.google.gson.Gson;

public class CreateSnapDealInventoryFeed {
        private static long time = System.currentTimeMillis();
        private static String SNAPDEAL_INVENTORY_SHEET;
        private static Map<Long, SnapdealItemForInventory> allItemsInventoryMap = new HashMap<Long, SnapdealItemForInventory>();
        private static ArrayList<Inventory> currentInventoryItemList;
        static Map<Long,Long> itemIdpendingOrdersMap;
        private static Map<String,InventoryHistory> inventoryhistoryItemMap;
        private static DefaultHttpClient client = new DefaultHttpClient();
        static Map<String,SnapdealItemDetails> snapdealItemMap = new HashMap<String,SnapdealItemDetails>();
        static Map<Long,SnapdealItemDetails> itemSnapdealMap = new HashMap<Long,SnapdealItemDetails>();
        static Map<String,PendingOrderInventoryHistory> PendingOrdersInventoryHistoryMap = new HashMap<String,PendingOrderInventoryHistory>();
        static long lastUpdatedInventoryTime = 0;
        static java.text.SimpleDateFormat sdf;
        static String emailFromAddress;
        static String password;
        static GmailUtils mailer;
        static String sendTo[];
        static StringBuffer notMappedItems =new StringBuffer();
        static{
                sdf = new java.text.SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
                emailFromAddress = "build@shop2020.in";
                password = "cafe@nes";
                mailer = new GmailUtils();
                //sendTo = new String[]{"vikram.raghav@shop2020.in"};
                sendTo = new String[]{ "sandeep.sachdeva@shop2020.in", "vikram.raghav@shop2020.in", "rajneesh.arora@shop2020.in",
                                "khushal.bhatia@shop2020.in","manoj.kumar@saholic.com","chaitnaya.vats@saholic.com",
                                "yukti.jain@shop2020.in","manisha.sharma@shop2020.in","chandan.kumar@shop2020.in","ankush.dhingra@shop2020.in"};
                itemIdpendingOrdersMap = new HashMap<Long,Long>();
                CatalogClient catalogServiceClient = null;
                try {
                        catalogServiceClient = new CatalogClient();
                } catch (TTransportException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                }
                in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = catalogServiceClient.getClient();
                List<SnapdealItemDetails> allSnapdealItems = null;
                try {
                        allSnapdealItems = catalogClient.getAllSnapdealItems();
                } catch (TException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                for(SnapdealItemDetails snapdealItem:allSnapdealItems){
                        snapdealItemMap.put(snapdealItem.getSkuAtSnapdeal(),snapdealItem);
                        itemSnapdealMap.put(snapdealItem.getItem_id(), snapdealItem);
                        //System.out.println("Creating Item and Snapdeal Map " + snapdealItem.getItem_id() + " " + snapdealItem.getSkuAtSnapdeal());
                }
                in.shop2020.model.v1.order.TransactionService.Client transactionClient = null;
                try {
                        transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
                        lastUpdatedInventoryTime = transactionClient.getSourceDetail(7).getLastUpdatedOn();
                        //System.out.println("Time is " + lastUpdatedInventoryTime);
                } catch (Exception e) {
                        try {
                                transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
                                lastUpdatedInventoryTime = transactionClient.getSourceDetail(7).getLastUpdatedOn();
                        } catch (Exception ex) {
                                ex.printStackTrace();
                        }
                }

        }

        private static void calculateinventory(){
                CatalogClient catalogServiceClient = null;
                Map<Long,ItemInventory> availability= new HashMap<Long,ItemInventory>();
                try {
                        catalogServiceClient = new CatalogClient();
                } catch (TTransportException e) {
                        e.printStackTrace();
                }
                in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = catalogServiceClient.getClient();
                try {
                        List<Item> aliveItems = catalogClient.getAllAliveItems();
                        Map<Long,Item> aliveItemsMap = new HashMap<Long,Item>(); 
                        for(in.shop2020.model.v1.catalog.Item thriftItem:aliveItems){
                                aliveItemsMap.put(thriftItem.getId(), thriftItem);

                        }
                        InventoryClient inventoryServiceClient = new InventoryClient();
                        try {
                                inventoryServiceClient = new InventoryClient();
                        } catch (TTransportException e) {
                                e.printStackTrace();
                        }
                        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                        List<in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems> ignoreItems = inventoryClient.getIgnoredWarehouseidsAndItemids();
                        SNAPDEAL_INVENTORY_SHEET = "/home/snapdeal/snapdeal-inventory-"+time+".xls";
                        availability = inventoryClient.getInventorySnapshot(0);
                        List<Warehouse> allwarehouses = inventoryClient.getWarehouses(null,null,0,0,0);
                        Map<Long,Warehouse> allWarehousesMap = new HashMap<Long,Warehouse>();
                        for(Warehouse warehouse:allwarehouses){
                                allWarehousesMap.put(warehouse.getId(),warehouse);
                        }
                        List<Warehouse> warehouses = inventoryClient.getWarehouses(WarehouseType.OURS_THIRDPARTY,null,0,0,0);
                        List<Warehouse> ours_warehouses = inventoryClient.getWarehouses(WarehouseType.OURS, InventoryType.GOOD, 0, 0, 0);
                        List<Long> thirdpartywarehouseids = new ArrayList<Long>();
                        List<Long> oursGoodWarehouse = new ArrayList<Long>();
                        for(Warehouse warehouse:warehouses){
                                thirdpartywarehouseids.add(warehouse.getId());
                        }
                        for (Warehouse warehouse:ours_warehouses){
                                oursGoodWarehouse.add(warehouse.getId());
                        }
                        long available=0;
                        long reserve=0;
                        long total_warehouse_held=0;
                        long heldForSource=0;
                        long total_held=0;
                        double nlc=0;
                        double maxnlc=0;
                        Item thriftItem;
                        long sku = 0;
                        for(Inventory inventoryItem:currentInventoryItemList){
                                if(snapdealItemMap.containsKey(inventoryItem.getSellerSku())){
                                        sku = snapdealItemMap.get(inventoryItem.getSellerSku()).getItem_id();
                                }
                                else{
                                        continue;
                                }
                                if(aliveItemsMap.get(sku) != null){
                                        thriftItem = aliveItemsMap.get(sku);    
                                }
                                else{
                                        continue;
                                }
                                available=0;
                                reserve=0;
                                total_warehouse_held=0;
                                heldForSource=0;
                                total_held=0;
                                nlc=0;
                                List<Warehouse> vendor_warehouses=null;
                                SnapdealItemForInventory item;
                                if(availability.get(thriftItem.getId())!=null){ 
                                        ItemInventory iteminventory = availability.get(thriftItem.getId());
                                        Map<Long,Long> itemavailability = new HashMap<Long,Long>();
                                        itemavailability = iteminventory.getAvailability();
                                        if (thriftItem.isIsWarehousePreferenceSticky() && thriftItem.getPreferredVendor()!=0){
                                                //System.out.println("Item id "+thriftItem.getId()+".Found prefered vendor and warehouse is marked sticky (Calculating availability)"+thriftItem.getPreferredVendor());                                         
                                                vendor_warehouses = inventoryClient.getWarehouses(WarehouseType.THIRD_PARTY,InventoryType.GOOD , thriftItem.getPreferredVendor(), 0, 0);
                                                vendor_warehouses.addAll(ours_warehouses);
                                                for (Warehouse warehouse:vendor_warehouses){
                                                        if(warehouse.getBillingWarehouseId()!=7){
                                                                if(warehouse.getLogisticsLocation().equals(WarehouseLocation.Delhi) && warehouse.getWarehouseType().equals(WarehouseType.THIRD_PARTY) && warehouse.getVendor().getId()!=1){

                                                                }
                                                                else{
                                                                        continue;
                                                                }
                                                        }
                                                        in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems ignoredItem = new in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems();
                                                        ignoredItem.setItemId(thriftItem.getId());
                                                        ignoredItem.setWarehouseId(warehouse.getId());
                                                        if (itemavailability.get(warehouse.getId())!=null && !thirdpartywarehouseids.contains(warehouse.getId()) && !ignoreItems.contains(ignoredItem)){
                                                                try{
                                                                        nlc = inventoryClient.getNlcForWarehouse(warehouse.getId(),thriftItem.getId());
                                                                }
                                                                catch(TTransportException e){
                                                                        inventoryClient = inventoryServiceClient.getClient(); 
                                                                        nlc = inventoryClient.getNlcForWarehouse(warehouse.getId(),thriftItem.getId());
                                                                }
                                                                maxnlc = catalogClient.getSnapdealItem(thriftItem.getId()).getMaxNlc();

                                                                //System.out.println("itemId:" + thriftItem.getId() + "\tmaxnlc: " + maxnlc + "\tnlc:" + nlc + "\twid:" + warehouse.getId() );
                                                                if(nlc !=0 && (maxnlc >= nlc)){
                                                                        total_warehouse_held = inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), warehouse.getId(), 0);
                                                                        heldForSource = heldForSource + total_warehouse_held - inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), warehouse.getId(), 7);
                                                                        available = available + itemavailability.get(warehouse.getId());
                                                                        total_held = total_held + total_warehouse_held; 
                                                                        //System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\tavailable:" + available);
                                                                }
                                                                else if(maxnlc==0){
                                                                        total_warehouse_held = inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), warehouse.getId(), 0);
                                                                        heldForSource = heldForSource + total_warehouse_held - inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), warehouse.getId(), 7);
                                                                        available = available + itemavailability.get(warehouse.getId());
                                                                        total_held = total_held + total_warehouse_held;
                                                                        //System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\tavailable:" + available);
                                                                }
                                                        }
                                                }
                                        }
                                        else{
                                                for (Map.Entry<Long,Long> entry :  itemavailability.entrySet()) {
                                                        if(allWarehousesMap.get(entry.getKey()).getBillingWarehouseId()!=7){
                                                                if(allWarehousesMap.get(entry.getKey()).getLogisticsLocation().equals(WarehouseLocation.Delhi) && allWarehousesMap.get(entry.getKey()).getWarehouseType().equals(WarehouseType.THIRD_PARTY) && allWarehousesMap.get(entry.getKey()).getVendor().getId()!=1){

                                                                }
                                                                else{
                                                                        continue;
                                                                }
                                                        }
                                                        in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems ignoredItem = new in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems();
                                                        ignoredItem.setItemId(thriftItem.getId());
                                                        ignoredItem.setWarehouseId(entry.getKey());
                                                        if(!thirdpartywarehouseids.contains(entry.getKey()) && !ignoreItems.contains(ignoredItem)){

                                                                nlc = inventoryClient.getNlcForWarehouse(entry.getKey(),thriftItem.getId());
                                                                try{
                                                                        maxnlc = catalogClient.getSnapdealItem(thriftItem.getId()).getMaxNlc();
                                                                }
                                                                catch(TTransportException e){
                                                                        catalogClient = catalogServiceClient.getClient();  
                                                                        maxnlc = catalogClient.getSnapdealItem(thriftItem.getId()).getMaxNlc();
                                                                }
                                                                //System.out.println("itemId:" + thriftItem.getId() + "\tmaxnlc: " + maxnlc + "\tnlc:" + nlc + "\twid:" + entry.getKey() );
                                                                if(nlc !=0 && (maxnlc >= nlc)){
                                                                        total_warehouse_held = inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), entry.getKey(), 0);
                                                                        heldForSource = heldForSource + total_warehouse_held - inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), entry.getKey(), 7);
                                                                        available =  available + entry.getValue();
                                                                        total_held = total_held + total_warehouse_held;
                                                                        //System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\tavailable:" + available);
                                                                }
                                                                else if(maxnlc==0){
                                                                        total_warehouse_held = inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), entry.getKey(), 0);
                                                                        heldForSource = heldForSource + total_warehouse_held - inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), entry.getKey(), 7);
                                                                        available = available + itemavailability.get(entry.getKey());
                                                                        total_held = total_held + total_warehouse_held;
                                                                        //System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\tavailable:" + available);
                                                                }

                                                        }
                                                }
                                        }
                                        Map<Long,Long> itemreserve = new HashMap<Long,Long>();
                                        itemreserve = iteminventory.getReserved();
                                        if (thriftItem.isIsWarehousePreferenceSticky() && thriftItem.getPreferredVendor()!=0){
                                                //System.out.println("Item id "+thriftItem.getId()+".Found prefered vendor and warehouse is marked sticky (Calculating Reserve)"+thriftItem.getPreferredVendor());
                                                for (Warehouse warehouse:vendor_warehouses){
                                                        if(warehouse.getBillingWarehouseId()!=7){
                                                                if(warehouse.getLogisticsLocation().equals(WarehouseLocation.Delhi) && warehouse.getWarehouseType().equals(WarehouseType.THIRD_PARTY) && warehouse.getVendor().getId()!=1){

                                                                }
                                                                else{
                                                                        continue;
                                                                }
                                                        }
                                                        in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems ignoredItem = new in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems();
                                                        ignoredItem.setItemId(thriftItem.getId());
                                                        ignoredItem.setWarehouseId(warehouse.getId());
                                                        if (itemreserve.get(warehouse.getId())!=null && !thirdpartywarehouseids.contains(warehouse.getId()) && !ignoreItems.contains(warehouse.getId())){
                                                                nlc = inventoryClient.getNlcForWarehouse(warehouse.getId(),thriftItem.getId());
                                                                maxnlc = catalogClient.getSnapdealItem(thriftItem.getId()).getMaxNlc();
                                                                //System.out.println("itemId:" + thriftItem.getId() + "\tmaxnlc: " + maxnlc + "\tnlc:" + nlc + "\twid:" + warehouse.getId() );
                                                                if(nlc !=0 && (maxnlc >= nlc)){
                                                                        reserve = reserve + itemreserve.get(warehouse.getId());
                                                                        //System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\treserve:" + reserve);
                                                                }
                                                                else if(maxnlc==0){
                                                                        reserve = reserve + itemreserve.get(warehouse.getId());
                                                                        //System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\treserve:" + reserve);
                                                                }

                                                        }
                                                }
                                        }else{
                                                for (Map.Entry<Long,Long> entry : itemreserve.entrySet()) {
                                                        if(allWarehousesMap.get(entry.getKey()).getBillingWarehouseId()!=7){
                                                                if(allWarehousesMap.get(entry.getKey()).getLogisticsLocation().equals(WarehouseLocation.Delhi) && allWarehousesMap.get(entry.getKey()).getWarehouseType().equals(WarehouseType.THIRD_PARTY) && allWarehousesMap.get(entry.getKey()).getVendor().getId()!=1){

                                                                }
                                                                else{
                                                                        continue;
                                                                }
                                                        }
                                                        in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems ignoredItem = new in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems();
                                                        ignoredItem.setItemId(thriftItem.getId());
                                                        ignoredItem.setWarehouseId(entry.getKey());
                                                        if(!thirdpartywarehouseids.contains(entry.getKey()) && !ignoreItems.contains(ignoredItem)){
                                                                nlc = inventoryClient.getNlcForWarehouse(entry.getKey(),thriftItem.getId());
                                                                maxnlc = catalogClient.getSnapdealItem(thriftItem.getId()).getMaxNlc();
                                                                //System.out.println("itemId:" + thriftItem.getId() + "\tmaxnlc: " + maxnlc + "\tnlc:" + nlc + "\twid:" + entry.getKey() );
                                                                if(nlc !=0 && (maxnlc >= nlc)){
                                                                        reserve =  reserve + entry.getValue();
                                                                        //System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\treserve:" + reserve);
                                                                }
                                                                else if(maxnlc==0){
                                                                        reserve =  reserve + entry.getValue();
                                                                        //System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\treserve:" + reserve);
                                                                }

                                                        }

                                                        else{
                                                                //System.out.println("skipping inventory for warehouse id " + entry.getKey());
                                                        }
                                                }
                                        }
                                        item= new SnapdealItemForInventory(thriftItem.getId(),available,reserve,heldForSource,thriftItem.getHoldInventory(),thriftItem.getDefaultInventory(),total_held,thriftItem.isRisky(),thriftItem.getItemStatus());
                                        //System.out.println("itemId:" + thriftItem.getId() + "\tavailable: " + available + "\treserve" + reserve + "\theldForSource:" + heldForSource + "\twebsite_hold:" + thriftItem.getHoldInventory() + "\tdefault_inv:" +thriftItem.getDefaultInventory());
                                }
                                else{
                                        item = new SnapdealItemForInventory(thriftItem.getId(),0,0,0,thriftItem.getHoldInventory(),thriftItem.getDefaultInventory(),0,thriftItem.isRisky(),thriftItem.getItemStatus());
                                        //System.out.println("itemId:" + thriftItem.getId() + "\tavailable: " + available + "\treserve" + reserve + "\theldForSource:" + heldForSource + "\twebsite_hold:" + thriftItem.getHoldInventory() + "\tdefault_inv:" +thriftItem.getDefaultInventory());
                                }

                                //System.out.println(" Item details are " + thriftItem.getId() +" " + available + " " + reserve + " " + thriftItem.getHoldInventory() + " "+ thriftItem.getDefaultInventory() + " " + thriftItem.isRisky());
                                //System.out.println("+++++++++++++++++++++++");
                                allItemsInventoryMap.put(thriftItem.getId(),item);

                        }

                } catch (TException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }

        }
        private static void fetchinventoryhistoryfromsnapdeal() throws UnsupportedEncodingException, TException{
                int i = 1;
                Gson gson = new Gson();
                inventoryhistoryItemMap = new HashMap<String,InventoryHistory>();
                boolean exitfetchinghistory = true;
                System.out.println("Fetching history inventory");
                HttpGet get;
                HttpResponse response = null;
                BufferedReader rd = null;
                while(exitfetchinghistory){
                        System.out.println("Fetching inventory history page " +i);
                        get = new HttpGet("http://seller.snapdeal.com/inventory/search?gridType=history&_search=false&nd="+time+"&rows=30&page="+i+"&sidx=&sord=dsc");

                        try {
                                response = client.execute(get);
                        } catch (ClientProtocolException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }

                        try {
                                rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                                
                        } catch (IllegalStateException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                        InventoryHistoryItems inventoryhistoryitems = (InventoryHistoryItems) gson.fromJson(rd, InventoryHistoryItems.class);
                        if(inventoryhistoryitems.getRows().size()!=0){
                                //System.out.println("Parsing page " + i);
                                for(InventoryHistory inventoryhistory : inventoryhistoryitems.getRows()){
                                        //System.out.println("Inventory History " + inventoryhistory.getSellerSku() +" "+ inventoryhistory.getSupc());
                                        if(inventoryhistory.getUpdateTime() > lastUpdatedInventoryTime){
                                                if(inventoryhistoryItemMap.containsKey(inventoryhistory.getSellerSku())){
                                                        if(inventoryhistoryItemMap.get(inventoryhistory.getSellerSku()).getUpdateTime() < inventoryhistory.getUpdateTime()){  
                                                                inventoryhistoryItemMap.put(inventoryhistory.getSellerSku(),inventoryhistory);
                                                        }
                                                }
                                                else{
                                                        inventoryhistoryItemMap.put(inventoryhistory.getSellerSku(),inventoryhistory);
                                                }
                                        }
                                        else{
                                                exitfetchinghistory = false;
                                        }
                                }
                        }
                        else{
                                exitfetchinghistory = false;
                        }
                        i++;
                }
                if(inventoryhistoryItemMap.entrySet().size()==0){
                        try {
                                mailer.sendSSLMessage(sendTo,"Error : Last Inventory Sent still not updated"+ sdf.format(System.currentTimeMillis()),"This e-mail is sent when there is some time lag on inventory updation on snapdeal ", emailFromAddress, password, new ArrayList<File>());
                        } catch (MessagingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                }
                InventoryClient inventoryServiceClient = new InventoryClient();
                in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                List<SnapdealInventoryItem> snapdealInventoryItemHistoryList = inventoryClient.getSnapdealInventorySnapshot();
                if(snapdealInventoryItemHistoryList.size()>0){
                        for(SnapdealInventoryItem snapdealInventoryItem:snapdealInventoryItemHistoryList){
                                if(itemSnapdealMap.containsKey(snapdealInventoryItem.getItem_id())){
                                        PendingOrderInventoryHistory pendingOrdersInventoryHistory = new PendingOrderInventoryHistory();
                                        pendingOrdersInventoryHistory.setPendingOrders(snapdealInventoryItem.getPendingOrders());
                                        pendingOrdersInventoryHistory.setInventoryHistory(snapdealInventoryItem.getAvailability());
                                        pendingOrdersInventoryHistory.setLastUpdatedTimestamp(snapdealInventoryItem.getLastUpdatedOnSnapdeal());
                                        PendingOrdersInventoryHistoryMap.put(itemSnapdealMap.get(snapdealInventoryItem.getItem_id()).getSkuAtSnapdeal(), pendingOrdersInventoryHistory);
                                }
                        }
                }
                PendingOrderInventoryHistory  pendingOrdersInventoryHistory;
                for(Entry<String, InventoryHistory> inventoryHistoryItem :inventoryhistoryItemMap.entrySet()){
                        if(PendingOrdersInventoryHistoryMap.containsKey(inventoryHistoryItem.getValue().getSellerSku())){
                                pendingOrdersInventoryHistory = PendingOrdersInventoryHistoryMap.get(inventoryHistoryItem.getValue().getSellerSku());
                                pendingOrdersInventoryHistory.setInventoryHistory(Long.parseLong(inventoryHistoryItem.getValue().getNewValue()));
                                pendingOrdersInventoryHistory.setLastUpdatedTimestamp(inventoryHistoryItem.getValue().getUpdateTime());
                                PendingOrdersInventoryHistoryMap.put(inventoryHistoryItem.getValue().getSellerSku(),pendingOrdersInventoryHistory);
                        }
                        else{
                                pendingOrdersInventoryHistory = new PendingOrderInventoryHistory();
                                pendingOrdersInventoryHistory.setInventoryHistory(Long.parseLong(inventoryHistoryItem.getValue().getNewValue()));
                                pendingOrdersInventoryHistory.setLastUpdatedTimestamp(inventoryHistoryItem.getValue().getUpdateTime());
                                pendingOrdersInventoryHistory.setPendingOrders(0);
                                PendingOrdersInventoryHistoryMap.put(inventoryHistoryItem.getValue().getSellerSku(),pendingOrdersInventoryHistory);
                        }
                }
        }

        private static void fetchcurrentinventoryfromsnapdeal() throws UnsupportedEncodingException, TException{
                int i = 1;
                int items=0;
                Gson gson = new Gson();
                in.shop2020.model.v1.order.TransactionService.Client transactionClient = null;
                currentInventoryItemList = new ArrayList<Inventory>();
                HttpGet get;
                HttpResponse response = null;
                BufferedReader rd= null;
                System.out.println("Fetching current inventory ");
                while(true){
                        //System.out.println("Fetching current inventory page " +i);
                        get = new HttpGet("http://seller.snapdeal.com/inventory/search?gridType=normal&_search=false&nd="+time+"&rows="+30+"&page="+i+"&sidx=&sord=asc");
                        try {
                                response = client.execute(get);
                        } catch (ClientProtocolException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                        try {
                                rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                        } catch (IllegalStateException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                        InventoryItems inventoryitems = (InventoryItems) gson.fromJson(rd, InventoryItems.class);
                        if(inventoryitems.getRows().size()!=0){
                                for(Inventory inventory : inventoryitems.getRows()){
                                        if(snapdealItemMap.containsKey(inventory.getSellerSku())){
                                                currentInventoryItemList.add(inventory);
                                        }

                                        else{
                                                notMappedItems.append("<tr>" 
                                                                + "<td>" + inventory.getProductName() +"</td>"
                                                                +"<td>" + inventory.getSellerSku() + "</td>"
                                                                +"<td>" + inventory.getSupc() + "</td>"
                                                                +"</tr>");
                                        }
                                        items++;
                                }
                        }
                        else{
                                System.out.println("Fetched  " + items);
                                break;
                        }
                        i++;
                }
                in.shop2020.model.v1.catalog.CatalogService.Client catalogServiceClient = null;
                SnapdealItemDetails snapdealitem = null;
                long sku = 0;
                long created_orders;
                long pending_orders;
                Map<Long, Long> itemIdCreatedOrdersMap = null;
                try {
                        transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
                        System.out.println("Last Updated on Time is  " + lastUpdatedInventoryTime);
                        if(lastUpdatedInventoryTime > 0){
                                itemIdCreatedOrdersMap = transactionClient.getOrdersCreatedAfterTimestampForSource(lastUpdatedInventoryTime, 7);
                                System.out.println("Item id orders created map size "+ itemIdCreatedOrdersMap.entrySet().size());
                        }
                } catch (TTransportException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                }
                try {
                        catalogServiceClient = new CatalogClient().getClient();
                } catch (TTransportException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                }
                List<String> notMappedItems = new ArrayList<String>();

                for(Inventory inventory:currentInventoryItemList){
                        created_orders = 0;
                        pending_orders = 0;
                        snapdealitem = snapdealItemMap.get(inventory.getSellerSku());
                        if(snapdealitem==null){
                                notMappedItems.add(inventory.getSellerSku()+" "+inventory.getProductName());
                                System.out.println("Not Mapped  " + inventory.getSellerSku());
                                continue;
                        }
                        sku = snapdealitem.getItem_id();
                        if(sku!=0){
                                if(itemIdCreatedOrdersMap!=null && itemIdCreatedOrdersMap.containsKey(sku)){
                                        created_orders = itemIdCreatedOrdersMap.get(sku);
                                }
                                System.out.println("Created orders for " + sku +" " + created_orders);
                        }
                        else{
                                continue;
                        }
                        if(PendingOrdersInventoryHistoryMap.containsKey(inventory.getSellerSku())){
                                System.out.println("Calculating Pending Orders for " + inventory.getSellerSku());
                                System.out.println("Current Inventory "+inventory.getAvailableInventory());
                                System.out.println("History Inventory "+PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getInventoryHistory());
                                System.out.println("Created Orders "+created_orders);
                                System.out.println("Old Pending Orders "+ PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getPendingOrders());
                                if(PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getLastUpdatedTimestamp() > lastUpdatedInventoryTime){
                                        pending_orders = PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getPendingOrders() + PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getInventoryHistory() - inventory.getAvailableInventory() - created_orders;
                                }
                                else{
                                        pending_orders = PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getPendingOrders() - created_orders;
                                }
                                if(pending_orders < 0){
                                        pending_orders = 0;
                                }
                                System.out.println("New Pending Orders "+pending_orders);
                                PendingOrderInventoryHistory pendingOrderInventoryHistory = PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku());
                                pendingOrderInventoryHistory.setPendingOrders(pending_orders);
                                PendingOrdersInventoryHistoryMap.put(inventory.getSellerSku(),pendingOrderInventoryHistory);
                        }
                        else{
                                System.out.print("Could not calculate pending orders " + inventory.getSellerSku() +"\n");
                                PendingOrderInventoryHistory pendingOrderInventoryHistory = new PendingOrderInventoryHistory();
                                pendingOrderInventoryHistory.setPendingOrders(pending_orders);
                                pendingOrderInventoryHistory.setInventoryHistory(inventory.getAvailableInventory());
                                pendingOrderInventoryHistory.setLastUpdatedTimestamp(System.currentTimeMillis());
                                PendingOrdersInventoryHistoryMap.put(inventory.getSellerSku(),pendingOrderInventoryHistory);
                        }
                        itemIdpendingOrdersMap.put(sku, pending_orders);

                }
                List<SnapdealInventoryItem> snapdealInventoryItemList = new ArrayList<SnapdealInventoryItem>();
                SnapdealInventoryItem snapdealInventoryItem;
                for(Entry<String, PendingOrderInventoryHistory> pendingOrderInventoryHistory:PendingOrdersInventoryHistoryMap.entrySet()){
                        snapdealInventoryItem = new SnapdealInventoryItem();
                        if(snapdealItemMap.containsKey(pendingOrderInventoryHistory.getKey())){
                                snapdealInventoryItem.setItem_id(snapdealItemMap.get(pendingOrderInventoryHistory.getKey()).getItem_id());
                                snapdealInventoryItem.setPendingOrders(pendingOrderInventoryHistory.getValue().getPendingOrders());
                                snapdealInventoryItem.setAvailability(pendingOrderInventoryHistory.getValue().getInventoryHistory());
                                snapdealInventoryItem.setLastUpdatedOnSnapdeal(pendingOrderInventoryHistory.getValue().getLastUpdatedTimestamp());
                                snapdealInventoryItemList.add(snapdealInventoryItem);
                        }
                }
                InventoryClient inventoryServiceClient = new InventoryClient();
                in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                try {
                        inventoryClient.addOrUpdateAllSnapdealInventory(snapdealInventoryItemList);
                } catch (TException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        inventoryClient = inventoryServiceClient.getClient();
                        inventoryClient.addOrUpdateAllSnapdealInventory(snapdealInventoryItemList);
                }

        }

        public static void handleLogin() throws ClientProtocolException, IOException{
                HttpGet get = new HttpGet("http://selleraccounts.snapdeal.com/login?service=http%3A%2F%2Fseller.snapdeal.com%2Fj_spring_cas_security_check");
                HttpResponse response = null;
                try {
                        response = client.execute(get);
                } catch (ClientProtocolException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                BufferedReader rd = null;
                try {
                        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                } catch (IllegalStateException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                }
                String line = "";
                StringBuffer sb = new StringBuffer();
                try {
                        while ((line = rd.readLine()) != null) {
                                sb.append(line);
                                //System.out.println(line);
                        }
                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                int i= sb.toString().indexOf("name=\"lt\" value=");
                char[] charArray = sb.toString().toCharArray();
                String lt = "";
                int j=0;
                for(j=i+16;j<=charArray.length;j++){

                        if(charArray[j]==' '){
                                break;
                        }
                }
                lt = sb.substring(i+17,j-1);
                System.out.println("LT VALUE " + lt);
                i= sb.toString().indexOf("name=\"execution\" value=");
                charArray = sb.toString().toCharArray();
                String ex = "";
                j=0;
                for(j=i+24;j<=charArray.length;j++){
                        if(charArray[j]==' '){
                                break;
                        }
                }
                ex = sb.substring(i+24,j-1);
                System.out.println("EXECUTION VALUE " + ex);
                HttpPost post = new HttpPost("http://selleraccounts.snapdeal.com/login?service=http%3A%2F%2Fseller.snapdeal.com%2Fj_spring_cas_security_check");
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                //nameValuePairs.add(new BasicNameValuePair("username",
                //"khushal.bhatia@saholic.com"));
                nameValuePairs.add(new BasicNameValuePair("username",
                "saholic-snapdeal@saholic.com"));
                //nameValuePairs.add(new BasicNameValuePair("password",
                //"sonline"));
                nameValuePairs.add(new BasicNameValuePair("password",
                "saholic15"));
                nameValuePairs.add(new BasicNameValuePair("_eventId","submit"));
                nameValuePairs.add(new BasicNameValuePair("execution",ex));
                nameValuePairs.add(new BasicNameValuePair("lt",lt));
                nameValuePairs.add(new BasicNameValuePair("submit","LOGIN"));
                post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
                response = client.execute(post);
                rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                line = "";
                while ((line = rd.readLine()) != null) {
                        System.out.println(line);
                }
                get = new HttpGet("http://seller.snapdeal.com/inventory/");
                response = client.execute(get);
                rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                while ((line = rd.readLine()) != null) {
                        //System.out.println(line);
                }
        }




        @SuppressWarnings("deprecation")
        public static void main(String[] args) throws NumberFormatException, TException, ClientProtocolException, IOException, MessagingException {
                handleLogin();
                fetchinventoryhistoryfromsnapdeal();
                fetchcurrentinventoryfromsnapdeal();
                calculateinventory();
                in.shop2020.model.v1.catalog.CatalogService.Client catalogServiceClient = null;
                try {
                        catalogServiceClient = new CatalogClient().getClient();
                } catch (TTransportException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                FileInputStream fis = new FileInputStream("/root/code/trunk/SnapDealFeeds/SellerInventory.xls");
                Workbook hwb = new HSSFWorkbook(fis);
                Sheet sheet = hwb.getSheetAt(0);
                Row row;
                int iterator=1;
                long available,reserve,defaultinventory,holdinventory,heldorders=0,sent_inventory = 0,totalheld,heldforsource,allocable;
                SnapdealItemForInventory  inventoryItem;
                StringBuffer outOfStockItems =new StringBuffer();
                StringBuffer backInStockItems =new StringBuffer();
                StringBuffer inventoryChangeItems =new StringBuffer();
                StringBuffer heldMoreThanAvailable =new StringBuffer();
                long sku = 0;
                SnapdealItemDetails snapdealitem;
                for(Inventory inventory:currentInventoryItemList){
                        //System.out.println(inventory.getSupc()+" "+inventory.getSellerSku()+ " " +inventory.getProductName()+" "+inventory.getAvailableInventory()+" "+inventory.isLive()+" "+itemIdpendingOrdersMap.get(Long.parseLong(inventory.getSellerSku())));
                        if(snapdealItemMap.containsKey(inventory.getSellerSku())){
                                snapdealitem = snapdealItemMap.get(inventory.getSellerSku()); 
                                sku =  snapdealitem.getItem_id();
                        }
                        else{
                                continue;
                        }
                        if(snapdealitem.getItem_id()!=0 && snapdealitem.isIsListedOnSnapdeal() && !snapdealitem.isSuppressInventoryFeed()){
                                inventoryItem = allItemsInventoryMap.get(sku);
                                if(inventoryItem==null){
                                        continue;
                                }
                                available = inventoryItem.getAvailability(); 
                                reserve = inventoryItem.getReserve();
                                defaultinventory = inventoryItem.getDefaultInventory();
                                holdinventory = inventoryItem.getHoldInventory();
                                totalheld = inventoryItem.getTotalHeldInventory();
                                heldforsource = inventoryItem.getHeldForSource();
                                if(itemIdpendingOrdersMap.containsKey(sku)){
                                        heldorders = itemIdpendingOrdersMap.get(sku);
                                        if(heldorders < 0){
                                                heldorders = 0;
                                        }
                                }
                                System.out.println("itemId: " + inventoryItem.getId() + "\trisky: " + inventoryItem.getRisky()+ 
                                                "\tavailable: " + available + "\treserve: " + reserve + "\theldForSource:" + heldforsource +
                                                "\twebsite_hold: " + holdinventory + "\ttotal_held: " +totalheld +"\tdefault_inv: "
                                                + defaultinventory + "\theldorders " + heldorders);
                                row =   sheet.getRow((short) iterator);
                                if(!inventoryItem.getStatus().equals(status.PAUSED)){
                                        if(inventoryItem.getRisky()){
                                                if((available - reserve) < totalheld && totalheld!=0){
                                                        sent_inventory = (long) Math.floor(((available - reserve)*heldforsource/totalheld)) - heldorders;
                                                        heldMoreThanAvailable.append("<tr>" 
                                                                        + "<td>" + inventory.getProductName() +"</td>"
                                                                        +"<td>" + sku + "</td>"
                                                                        +"<td>" + (available - reserve) +  "</td>"
                                                                        +"<td>" + totalheld + "</td>"
                                                                        +"</tr>");
                                                }
                                                else{
                                                        allocable = available - reserve - totalheld - holdinventory;
                                                        if(allocable < 0){
                                                                allocable = 0;
                                                        }
                                                        sent_inventory = Math.round(allocable*2/3) + heldforsource - heldorders ;
                                                }
                                                if(sent_inventory < 0){
                                                        sent_inventory = 0;
                                                }
                                        }
                                        else{
                                                allocable = available - reserve - totalheld;
                                                if(allocable < 0){
                                                        allocable = 0;
                                                }
                                                if((allocable + heldforsource ) > defaultinventory){
                                                        sent_inventory = Math.round(allocable*2/3) +  heldforsource - heldorders;
                                                        //System.out.println("actual" + allocable + "\t2/3actual" + Math.round(allocable*2/3) +  "\theld for source" + heldforsource + "\theldorders" +  heldorders + "\tFinal Value is : " + (Math.round(allocable*2/3) +  heldforsource - heldorders));
                                                        if(sent_inventory < 0){
                                                                sent_inventory = 0;                                                     
                                                        }
                                                }
                                                else{
                                                        if(defaultinventory > heldorders){
                                                                sent_inventory = defaultinventory - heldorders;
                                                        }
                                                        else{
                                                                sent_inventory = 0;
                                                        }
                                                }
                                        }
                                }
                                else{
                                        sent_inventory = 0;
                                }
                                if(inventory.getAvailableInventory()!= sent_inventory){
                                        row.getCell((short) 0).setCellValue(inventory.getSupc());
                                        row.getCell((short) 1).setCellValue(inventory.getSellerSku());
                                        row.getCell((short) 2).setCellValue(inventory.getProductName());
                                        row.getCell((short) 3).setCellValue(inventory.getAvailableInventory());
                                        row.getCell((short) 4).setCellValue(sent_inventory);
                                        if(inventory.getAvailableInventory()!=0 && sent_inventory==0){
                                                outOfStockItems.append("<tr>" 
                                                                + "<td>" + inventory.getProductName() +"</td>"
                                                                +"<td>" + sku + "</td>"
                                                                +"<td>" + inventory.getAvailableInventory() + "</td>"
                                                                +"<td>" + sent_inventory + "</td>"
                                                                +"</tr>");
                                        }
                                        else if(inventory.getAvailableInventory()==0 && sent_inventory!=0){
                                                backInStockItems.append("<tr>" 
                                                                + "<td>" + inventory.getProductName() +"</td>"
                                                                +"<td>" + sku + "</td>"
                                                                +"<td>" + inventory.getAvailableInventory() + "</td>"
                                                                +"<td>" + sent_inventory + "</td>"
                                                                +"</tr>");
                                        }
                                        else{
                                                inventoryChangeItems.append("<tr>" 
                                                                + "<td>" + inventory.getProductName() +"</td>"
                                                                +"<td>" + sku + "</td>"
                                                                +"<td>" + inventory.getAvailableInventory() + "</td>"
                                                                +"<td>" + sent_inventory + "</td>"
                                                                +"</tr>");
                                        }
                                        if(inventory.isLive()){
                                                row.getCell((short) 5).setCellValue("Yes");
                                        }
                                        else{
                                                row.getCell((short) 5).setCellValue("No");
                                        }
                                        iterator++;
                                }
                        }
                        else{
                                continue;
                        }
                }
                if(iterator > 1){
                        FileOutputStream fileOut = null;
                        fis.close();
                        try {
                                System.out.println("Before writing file ");
                                fileOut = new FileOutputStream(SNAPDEAL_INVENTORY_SHEET);
                        } catch (FileNotFoundException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                        try {

                                hwb.write(fileOut);
                        } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                        HttpPost post = new HttpPost("http://seller.snapdeal.com/inventory/upload");
                        File file = new File(SNAPDEAL_INVENTORY_SHEET);
                        MultipartEntity mpEntity = new MultipartEntity();
                        ContentBody cbFile = new FileBody(file,"application/vnd.ms-excel");
                        mpEntity.addPart("file", cbFile);
                        post.setEntity(mpEntity);
                        System.out.println("Before posting file");
                        HttpResponse response = client.execute(post);
                        BufferedReader rd = null;
                        try {
                                rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                        } catch (IllegalStateException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                        } catch (IOException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                        }
                        String line = "";
                        String feedresponse = null;
                        try {
                                while ((line = rd.readLine()) != null) {
                                        System.out.println(line);
                                        feedresponse = line;
                                }
                        } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                        System.out.println("posting response" + feedresponse);
                        in.shop2020.model.v1.order.TransactionService.Client transactionClient = null;
                        long lastSentInventoryTime = System.currentTimeMillis();
                        try {
                                transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
                                transactionClient.updateSourceDetailTimestamp(7, lastSentInventoryTime);
                        } catch (Exception e) {
                                try {
                                        transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
                                        transactionClient.updateSourceDetailTimestamp(7, lastSentInventoryTime);
                                } catch (Exception ex) {
                                        ex.printStackTrace();
                                }
                        }
                        String emailSubjectTxt = "Products back in stock on Snapdeal "+sdf.format(lastSentInventoryTime);
                        String text;
                        String tableHeader = "<tr>" 
                                + "<td>" + "Product Name" +"</td>"
                                +"<td>" + "Item ID" + "</td>"
                                +"<td>" + "Old Inventory" + "</td>"
                                +"<td>" + "New Inventory" + "</td>"
                                +"</tr>";
                        if(backInStockItems.length() > 0){
                                text = "<html><table border=\"1\" align=\"center\">"+tableHeader+backInStockItems.toString()+"</table></html>";
                                try {
                                        mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
                                        //mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
                                } catch (MessagingException e) {
                                        e.printStackTrace();
                                }
                        }
                        emailSubjectTxt = "Products out of stock on Snapdeal "+sdf.format(lastSentInventoryTime);
                        if(outOfStockItems.length() > 0){
                                text = "<html><table border=\"1\" align=\"center\">"+tableHeader+outOfStockItems.toString()+"</table></html>";
                                try {
                                        mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
                                        //mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
                                } catch (MessagingException e) {
                                        e.printStackTrace();
                                }
                        }
                        /*                      List<File> files = new ArrayList<File>();
                        files.add(new File(SNAPDEAL_INVENTORY_SHEET));
                        try {
                                mailer.sendSSLMessage(sendTo,"Inventory File",feedresponse, emailFromAddress, password, files);
                        } catch (MessagingException e) {
                                e.printStackTrace();
                        }
                         */
                        emailSubjectTxt = "Snapdeal Inventory Updates sent for " +(iterator-1)+" items "+ sdf.format(System.currentTimeMillis());
                        if(inventoryChangeItems.length() > 0){
                                text = "<html><table border=\"1\" align=\"center\">"+tableHeader+inventoryChangeItems.toString()+"</table></html>";
                                try {
                                        mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
                                } catch (MessagingException e) {
                                        e.printStackTrace();
                                }
                        }

                        tableHeader = "<tr>" 
                                + "<td>" + "Product Name" +"</td>"
                                +"<td>" + "Item ID" + "</td>"
                                +"<td>" + "Available - Reserve" + "</td>"
                                +"<td>" + "Total Held" + "</td>"
                                +"</tr>";

                        emailSubjectTxt = "Items with (Total Held > Net Available) Inventory "+ sdf.format(System.currentTimeMillis());
                        if(heldMoreThanAvailable.length() > 0){
                                text = "<html><table border=\"1\" align=\"center\">"+tableHeader+heldMoreThanAvailable.toString()+"</table></html>";
                                try {
                                        mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
                                        //mailer.sendSSLMessage(sendTo,"Snapdeal Inventory Updates sent for " +(iterator-1)+" items "+ sdf.format(System.currentTimeMillis()),inventoryChangeItems.toString(), emailFromAddress, password, new ArrayList<File>());
                                } catch (MessagingException e) {
                                        e.printStackTrace();
                                }
                        }

                }
                else{
                        try {
                                mailer.sendSSLMessage(sendTo,"No changes in Snapdeal inventory to update "+ sdf.format(System.currentTimeMillis()),"No change in Snapdeal Inventory to be updated ", emailFromAddress, password, new ArrayList<File>());
                        } catch (MessagingException e) {
                                e.printStackTrace();
                        }
                }
                String tableHeader = "<tr>" 
                        + "<td>" + "Product Name" +"</td>"
                        +"<td>" + "SKU at Snapdeal" + "</td>"
                        +"<td>" + "SUPC" + "</td>"
                        +"</tr>";
                String text;

                if(notMappedItems.length() >0){
                        text = "<html><table border=\"1\" align=\"center\">"+tableHeader+notMappedItems.toString()+"</table></html>";
                        mailer.sendSSLMessage(sendTo,"Please create Warehouse ID and Item ID mapping", emailFromAddress, password, text);
                }

        }

}