Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.support.controllers;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.xwork.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.util.ServletContextAware;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ValidationAwareSupport;

import in.shop2020.model.v1.catalog.CatalogService.Client;
import in.shop2020.model.v1.catalog.CatalogServiceException;
import in.shop2020.model.v1.catalog.GstRate;
import in.shop2020.model.v1.catalog.Item;
import in.shop2020.model.v1.catalog.ItemPricing;
import in.shop2020.model.v1.catalog.StateGstRate;
import in.shop2020.model.v1.dtr.BulkItems;
import in.shop2020.model.v1.inventory.BulkAddInventory;
import in.shop2020.model.v1.inventory.InventoryServiceException;
import in.shop2020.model.v1.inventory.ItemInventory;
import in.shop2020.model.v1.inventory.Vendor;
import in.shop2020.model.v1.inventory.VendorItemPricing;
import in.shop2020.model.v1.inventory.Warehouse;
import in.shop2020.support.utils.ReportsUtils;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.DtrClient;
import in.shop2020.thrift.clients.InventoryClient;

@SuppressWarnings({"unused","deprecation"})

@InterceptorRefs({
        @InterceptorRef("defaultStack"),
        @InterceptorRef("login")
})

public class BulkAddController extends ValidationAwareSupport implements ServletRequestAware ,ServletResponseAware, ServletContextAware{
        /**
         * 
         */
        private static final long serialVersionUID = 1L;


        private static Logger logger = LoggerFactory.getLogger(BulkAddController.class);


        private HttpServletRequest request;
        private HttpServletResponse response;
        private HttpSession session;
        private ServletContext context;
        private String id;
        private String result;
        private File file;
        private String virtualWarehouseId;

        public String getVirtualWarehouseId() {
                return virtualWarehouseId;
        }

        public void setVirtualWarehouseId(String virtualWarehouseId) {
                this.virtualWarehouseId = virtualWarehouseId;
        }

        public String index() {
                if (!ReportsUtils.canAccessReport((Long) session.getAttribute(ReportsUtils.ROLE),request.getServletPath())) {
                        return "authfail";
                }
                return "index";
        }

        public String edit() {
                if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1])) {
                        return "authfail";
                }
                return "edit";
        }


        public String show() {
                if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1])) {
                        return "authfail";
                }
                logger.info("Inside show for "+id);

                if (StringUtils.equals(id, "bulk-add-options")){
                        return "bulk-add-options";
                }
                return "id";
        }

        public String loadVendorDiv(){
                if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0])) {
                        logger.info(request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0]);
                        return "authfail";
                }
                return "vendor-item-pricing-upload";
        }

        public String loadVirtualDiv(){
                if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0])) {
                        logger.info(request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0]);
                        return "authfail";
                }
                return "virtual-bulk-add";
        }

        public String loadCatalogDiv(){
                if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0])) {
                        logger.info(request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0]);
                        return "authfail";
                }
                return "catalog-bulk-add";
        }

        public String loadDtrDiv(){
                if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0])) {
                        logger.info(request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0]);
                        return "authfail";
                }
                return "dtr-bulk-add";
        }
        
        public String loadDownloadVirtualDiv(){
                if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0])) {
                        logger.info(request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0]);
                        return "authfail";
                }
                return "download-virtual-div";
        }

        public String uploadItemsDtr() throws IOException, CatalogServiceException, TException{
                if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0])) {
                        logger.info(request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0]);
                        return "authfail";
                }
                File fileToCreate = new File("/tmp/", "dtr-items.xls");
                FileUtils.copyFile(this.file, fileToCreate);
                FileInputStream iFile = new FileInputStream(new File(file.getAbsolutePath()));
                HSSFWorkbook workbook = new HSSFWorkbook(iFile);
                HSSFSheet sheet = workbook.getSheetAt(0);

                List<BulkItems> bulkItemsList= new ArrayList<BulkItems>();

                List<Long> items = new ArrayList<Long>();

                for (int iterator=sheet.getFirstRowNum()+1;iterator<=sheet.getLastRowNum();iterator++){
                        long item_id = (long) sheet.getRow(iterator).getCell(0).getNumericCellValue();
                        items.add(item_id);
                }

                Client cc = new CatalogClient().getClient();
                Map<Long, Item> itemMap = cc.getItems(items);
                StringBuilder sb = new StringBuilder(); 
                for (int iterator=sheet.getFirstRowNum()+1;iterator<=sheet.getLastRowNum();iterator++){
                        long itemId = (long) sheet.getRow(iterator).getCell(0).getNumericCellValue();
                        Item t_item = itemMap.get(itemId);
                        if (t_item==null){
                                sb.append("Item is not valid "+itemId+"\n");
                                continue;
                        }
                        BulkItems b = new BulkItems();
                        b.setItem_id(itemId);

                        if (checkEmptyString(sheet.getRow(iterator).getCell(1))){
                                b.setShowMrpFlag(false);
                        }
                        else{
                                int show_mrp_flag = (int) sheet.getRow(iterator).getCell(1).getNumericCellValue();
                                b.setShowMrpFlag(show_mrp_flag ==1 ? true : false);
                        }
                        if (checkEmptyString(sheet.getRow(iterator).getCell(2))){
                                b.setTagline("");
                        }
                        else{
                                String tagline = sheet.getRow(iterator).getCell(2).getStringCellValue();
                                b.setTagline(tagline);
                        }
                        if (checkEmptyString(sheet.getRow(iterator).getCell(3))){
                                b.setOffer("");
                        }
                        else{
                                String offer = sheet.getRow(iterator).getCell(3).getStringCellValue();
                                b.setOffer(offer);
                        }
                        long category_id = (long) sheet.getRow(iterator).getCell(4).getNumericCellValue();
                        if (category_id!=6L){
                                sb.append("Category Id is not valid "+itemId+"\n");
                        }
                        b.setCategory_id(category_id);
                        long sub_category_id = (long) sheet.getRow(iterator).getCell(5).getNumericCellValue();
                        if (sub_category_id==0){
                                sb.append("SubCategory Id is not valid "+itemId+"\n");
                        }
                        b.setSubCategoryId(sub_category_id);
                        int show_net_price = (int) sheet.getRow(iterator).getCell(6).getNumericCellValue();
                        b.setShowNetPrice(show_net_price ==1 ? true : false);
                        long brand_id = (long) sheet.getRow(iterator).getCell(7).getNumericCellValue();
                        if (brand_id==0){
                                sb.append("Brand Id is not valid "+itemId+"\n");
                        }
                        long internalRank = (long) sheet.getRow(iterator).getCell(8).getNumericCellValue();
                        b.setInternalRank(internalRank);
                        b.setBrand_id(brand_id);
                        b.setAvailable_price(t_item.getSellingPrice());
                        b.setMrp(t_item.getMrp());
                        b.setBrand(t_item.getBrand());
                        b.setIdentifier(String.valueOf(t_item.getCatalogItemId()));
                        b.setModel_name(t_item.getModelName()+" "+t_item.getModelNumber());
                        b.setProduct_name(t_item.getBrand()+" "+t_item.getModelName()+" "+t_item.getModelNumber());
                        b.setSource_product_name(t_item.getBrand()+" "+t_item.getModelName()+" "+t_item.getModelNumber());
                        b.setQuantity(t_item.getPackQuantity());
                        bulkItemsList.add(b);
                }
                if (sb.length()>0){
                        setResult("Please correct error \n"+sb.toString());
                        return "item-details-json";
                }
                in.shop2020.model.v1.dtr.DtrService.Client dc = new DtrClient("dtr_service_server_host","dtr_service_server_port").getClient(); 
                List<String> res = dc.addItemsInBulk(bulkItemsList);
                if (res.size()>0){
                        for(String s : res){
                                sb.append("Catalog ItemId not added "+s+"\n");
                        }
                        setResult(sb.toString());
                }else{
                        setResult("Items added successfully");
                }
                return "item-details-json";
        }
        
        public String uploadTaxRateSheet() throws IOException, CatalogServiceException, TException{
                if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0])) {
                        logger.info(request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0]);
                        return "authfail";
                }
                File fileToCreate = new File("/tmp/", "tax-rate-sheet.xls");
                FileUtils.copyFile(this.file, fileToCreate);
                FileInputStream iFile = new FileInputStream(new File(file.getAbsolutePath()));
                HSSFWorkbook workbook = new HSSFWorkbook(iFile);
                HSSFSheet sheet = workbook.getSheetAt(0);

                List<Long> itemIdsTaxRates = new ArrayList<Long>();
                
                Map<Long, Double> itemIdIgstTaxRate = new HashMap<Long, Double>();
                List<StateGstRate> stateGstRates = new ArrayList<StateGstRate>();

                for (int iterator = sheet.getFirstRowNum() + 1; iterator <= sheet.getLastRowNum(); iterator++) {
                        long itemId = (long) sheet.getRow(iterator).getCell(0).getNumericCellValue();
                        double taxRate = sheet.getRow(iterator).getCell(1).getNumericCellValue();
                        StateGstRate sgr = new StateGstRate();
                        sgr.setItemId(itemId);
                        sgr.setIgstRate(taxRate);
                        stateGstRates.add(sgr);
                }

                Client cc = new CatalogClient().getClient();
                cc.persistGstRate(stateGstRates);
                
                setResult("Sheet uploaded successfully");
                return "item-details-json";
        }

        public String updateVirtualInventory() throws IOException, CatalogServiceException, TException, InventoryServiceException{
                if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0])) {
                        logger.info(request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0]);
                        return "authfail";
                }

                File fileToCreate = new File("/tmp/", "vendor-inventory.xls");
                FileUtils.copyFile(this.file, fileToCreate);
                FileInputStream iFile = new FileInputStream(new File(file.getAbsolutePath()));
                HSSFWorkbook workbook = new HSSFWorkbook(iFile);
                HSSFSheet sheet = workbook.getSheetAt(0);

                List<BulkAddInventory> vendorInventory= new ArrayList<BulkAddInventory>();

                List<Long> items = new ArrayList<Long>();

                for (int iterator=sheet.getFirstRowNum()+1;iterator<=sheet.getLastRowNum();iterator++){
                        long item_id = (long) sheet.getRow(iterator).getCell(0).getNumericCellValue();
                        items.add(item_id);
                }
                Client cc = new CatalogClient().getClient();
                Map<Long, Item> itemMap = cc.getItems(items);

                for (int iterator=sheet.getFirstRowNum()+1;iterator<=sheet.getLastRowNum();iterator++){
                        long itemId = (long) sheet.getRow(iterator).getCell(0).getNumericCellValue();
                        if (itemMap.get(itemId)==null){
                                continue;
                        }
                        BulkAddInventory b = new BulkAddInventory();
                        b.setItem_id(itemId);
                        long warehouseId = (long) sheet.getRow(iterator).getCell(1).getNumericCellValue();
                        b.setWarehouse_id(warehouseId);
                        long inventory = (long) sheet.getRow(iterator).getCell(2).getNumericCellValue();
                        b.setInventory(inventory);
                        vendorInventory.add(b);
                }

                InventoryClient inventoryServiceClient = new InventoryClient();
                in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                inventoryClient.addInventoryInBulk(vendorInventory);
                setResult("Inventory updated successfully");
                return "item-details-json";
        }

        public String addVendorItemPricing() throws IOException, TException, CatalogServiceException{
                if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0])) {
                        logger.info(request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0]);
                        return "authfail";
                }
                File fileToCreate = new File("/tmp/", "vendor-pricing.xls");
                FileUtils.copyFile(this.file, fileToCreate);
                FileInputStream iFile = new FileInputStream(new File(file.getAbsolutePath()));
                HSSFWorkbook workbook = new HSSFWorkbook(iFile);
                HSSFSheet sheet = workbook.getSheetAt(0);

                List<VendorItemPricing> vendorItemPricingList= new ArrayList<VendorItemPricing>();
                List<Long> items = new ArrayList<Long>();

                for (int iterator=sheet.getFirstRowNum()+1;iterator<=sheet.getLastRowNum();iterator++){
                        long item_id = (long) sheet.getRow(iterator).getCell(0).getNumericCellValue();
                        items.add(item_id);
                }
                Client cc = new CatalogClient().getClient();
                Map<Long, Item> itemMap = cc.getItems(items);

                for (int iterator=sheet.getFirstRowNum()+1;iterator<=sheet.getLastRowNum();iterator++){
                        long itemId = (long) sheet.getRow(iterator).getCell(0).getNumericCellValue();
                        if (itemMap.get(itemId)==null){
                                continue;
                        }
                        VendorItemPricing v = new VendorItemPricing();
                        v.setItemId(itemId);
                        long vendorId = (long) sheet.getRow(iterator).getCell(1).getNumericCellValue();
                        v.setVendorId(vendorId);
                        double mop = (double) sheet.getRow(iterator).getCell(2).getNumericCellValue();
                        v.setMop(mop);
                        double dp = (double) sheet.getRow(iterator).getCell(3).getNumericCellValue();
                        v.setDealerPrice(dp);
                        double tp = (double) sheet.getRow(iterator).getCell(4).getNumericCellValue();
                        v.setTransferPrice(tp);
                        double nlc = (double) sheet.getRow(iterator).getCell(5).getNumericCellValue();
                        v.setNlc(nlc);
                        vendorItemPricingList.add(v);
                }

                InventoryClient inventoryServiceClient = new InventoryClient();
                in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                List<Long> notUpdated = inventoryClient.addVendorItemPricingInBulk(vendorItemPricingList);

                if (notUpdated.size() > 0){
                        StringBuilder sb = new StringBuilder();
                        for (Long x : notUpdated){
                                sb.append("Vendor Pricing not updated for "+x+"\n");
                        }
                        setResult(sb.toString());
                }
                else{
                        setResult("Vendor item pricing updated.");
                }
                return "item-details-json";
        }

        public String updateItemPricing() throws IOException, CatalogServiceException, TException{
                if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0])) {
                        logger.info(request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0]);
                        return "authfail";
                }
                File fileToCreate = new File("/tmp/", "item-pricing.xls");
                FileUtils.copyFile(this.file, fileToCreate);
                FileInputStream iFile = new FileInputStream(new File(file.getAbsolutePath()));
                HSSFWorkbook workbook = new HSSFWorkbook(iFile);
                HSSFSheet sheet = workbook.getSheetAt(0);

                List<ItemPricing> itemPricingList= new ArrayList<ItemPricing>();
                List<Long> items = new ArrayList<Long>();

                for (int iterator=sheet.getFirstRowNum()+1;iterator<=sheet.getLastRowNum();iterator++){
                        long item_id = (long) sheet.getRow(iterator).getCell(0).getNumericCellValue();
                        items.add(item_id);
                }
                Client cc = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
                Map<Long, Item> itemMap = cc.getItems(items);

                for (int iterator=sheet.getFirstRowNum()+1;iterator<=sheet.getLastRowNum();iterator++){
                        ItemPricing i = new ItemPricing();
                        long item_id = (long) sheet.getRow(iterator).getCell(0).getNumericCellValue();
                        i.setItem_id(item_id);
                        if (itemMap.get(item_id)!=null){
                                if (checkEmptyString(sheet.getRow(iterator).getCell(1))){
                                        i.setSelling_price(itemMap.get(item_id).getSellingPrice());
                                }
                                else{
                                        double sellingPrice = (double) sheet.getRow(iterator).getCell(1).getNumericCellValue();
                                        i.setSelling_price(sellingPrice);
                                }
                                if (checkEmptyString(sheet.getRow(iterator).getCell(2))){
                                        i.setMrp(itemMap.get(item_id).getMrp());
                                }
                                else{
                                        double mrp = (double) sheet.getRow(iterator).getCell(2).getNumericCellValue();
                                        i.setMrp(mrp);
                                }
                                if (checkEmptyString(sheet.getRow(iterator).getCell(3))){
                                        i.setPreferred_vendor(itemMap.get(item_id).getPreferredVendor());
                                }
                                else{
                                        long preferred_vendor = (long) sheet.getRow(iterator).getCell(3).getNumericCellValue();
                                        i.setPreferred_vendor(preferred_vendor);
                                }
                                if (checkEmptyString(sheet.getRow(iterator).getCell(4))){
                                        i.setPrivate_deal_price(0);
                                }
                                else{
                                        double private_deal_price = (double) sheet.getRow(iterator).getCell(4).getNumericCellValue();
                                        i.setPrivate_deal_price(private_deal_price);
                                }
                                if (checkEmptyString(sheet.getRow(iterator).getCell(5))){
                                        i.setWeight(itemMap.get(item_id).getWeight());
                                }
                                else{
                                        double weight = (double) sheet.getRow(iterator).getCell(5).getNumericCellValue();
                                        i.setWeight(weight);
                                }
                                itemPricingList.add(i);
                        }
                }
                boolean res = cc.updateItemPricing(itemPricingList);
                if (res){
                        setResult("Pricing updated successfully");
                }
                else{
                        setResult("Unable to update pricing");
                }
                return "item-details-json";
        }

        public String downloadVendors() throws TException, IOException{
                if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0])) {
                        logger.info(request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0]);
                        return "authfail";
                }
                InventoryClient inventoryServiceClient = new InventoryClient();
                in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                List<Vendor> vendors = inventoryClient.getAllVendors();

                File file = new File("/tmp/vendors.xls");
                HSSFWorkbook hwb=new HSSFWorkbook();
                HSSFSheet sheet =  hwb.createSheet("Vendors");
                HSSFRow rowhead=   sheet.createRow((short)0);
                rowhead.createCell((short) 0).setCellValue("VENDOR_ID");
                rowhead.createCell((short) 1).setCellValue("VENDOR_NAME");

                int iterator= 1;
                for (Vendor v : vendors){
                        HSSFRow row = sheet.createRow((short)iterator);
                        row.createCell((short) 0).setCellValue(v.getId());
                        row.createCell((short) 1).setCellValue(v.getName());
                        iterator++;
                }

                FileOutputStream fileOut = null;
                try {
                        fileOut = new FileOutputStream(file);
                } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                try {
                        hwb.write(fileOut);
                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                try {
                        fileOut.close();
                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                byte[] buffer = new byte[(int)file.length()];
                InputStream input = null;
                try {
                        int totalBytesRead = 0;
                        input = new BufferedInputStream(new FileInputStream(file));
                        while(totalBytesRead < buffer.length){
                                int bytesRemaining = buffer.length - totalBytesRead;
                                int bytesRead = input.read(buffer, totalBytesRead, bytesRemaining); 
                                if (bytesRead > 0){
                                        totalBytesRead = totalBytesRead + bytesRead;
                                }
                        }
                }
                finally {
                        input.close();
                        file.delete();
                }

                response.setHeader("Content-Disposition", "attachment; filename=\"Vendors.xls\"");
                response.setContentType("application/octet-stream");
                ServletOutputStream sos;
                try {
                        sos = response.getOutputStream();
                        sos.write(buffer);
                        sos.flush();
                } catch (IOException e) {
                        System.out.println("Unable to stream the manifest file");
                }
                setResult("Vendor Streaming done");
                return "item-details-json";

        }

        public String downloadWarehouses() throws TException, IOException{
                if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0])) {
                        logger.info(request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0]);
                        return "authfail";
                }
                InventoryClient inventoryServiceClient = new InventoryClient();
                in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                List<Warehouse> warehouses = inventoryClient.getWarehouses(null, null, 0, 0, 0);

                File file = new File("/tmp/warehouses.xls");
                HSSFWorkbook hwb=new HSSFWorkbook();
                HSSFSheet sheet =  hwb.createSheet("Warehouses");
                HSSFRow rowhead=   sheet.createRow((short)0);
                rowhead.createCell((short) 0).setCellValue("warehouse_id");
                rowhead.createCell((short) 1).setCellValue("display_name");
                rowhead.createCell((short) 2).setCellValue("location");
                rowhead.createCell((short) 3).setCellValue("vendor_id");
                rowhead.createCell((short) 4).setCellValue("vendor_name");
                rowhead.createCell((short) 5).setCellValue("inventory_type");
                rowhead.createCell((short) 6).setCellValue("warehouse_type");
                rowhead.createCell((short) 7).setCellValue("logistics_location");
                rowhead.createCell((short) 8).setCellValue("state_id");

                int iterator= 1;
                for (Warehouse w : warehouses){
                        HSSFRow row = sheet.createRow((short)iterator);
                        row.createCell((short) 0).setCellValue(w.getId());
                        row.createCell((short) 1).setCellValue(w.getDisplayName());
                        row.createCell((short) 2).setCellValue(w.getLocation());
                        row.createCell((short) 3).setCellValue(w.getVendor().getId());
                        row.createCell((short) 4).setCellValue(w.getVendor().getName());
                        row.createCell((short) 5).setCellValue(w.getInventoryType().toString());
                        row.createCell((short) 6).setCellValue(w.getWarehouseType().toString());
                        row.createCell((short) 7).setCellValue(w.getLogisticsLocation().toString());
                        row.createCell((short) 7).setCellValue(w.getStateId());
                        iterator++;
                }

                FileOutputStream fileOut = null;
                try {
                        fileOut = new FileOutputStream(file);
                } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                try {
                        hwb.write(fileOut);
                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                try {
                        fileOut.close();
                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                byte[] buffer = new byte[(int)file.length()];
                InputStream input = null;
                try {
                        int totalBytesRead = 0;
                        input = new BufferedInputStream(new FileInputStream(file));
                        while(totalBytesRead < buffer.length){
                                int bytesRemaining = buffer.length - totalBytesRead;
                                int bytesRead = input.read(buffer, totalBytesRead, bytesRemaining); 
                                if (bytesRead > 0){
                                        totalBytesRead = totalBytesRead + bytesRead;
                                }
                        }
                }
                finally {
                        input.close();
                        file.delete();
                }

                response.setHeader("Content-Disposition", "attachment; filename=\"Warehouses.xls\"");
                response.setContentType("application/octet-stream");
                ServletOutputStream sos;
                try {
                        sos = response.getOutputStream();
                        sos.write(buffer);
                        sos.flush();
                } catch (IOException e) {
                        System.out.println("Unable to stream the manifest file");
                }
                setResult("Warehouse Streaming done");
                return "item-details-json";

        }

        public String downloadVirtualInventoryForWarehouse() throws NumberFormatException, TException, IOException{
                try{
                        InventoryClient inventoryServiceClient = new InventoryClient();
                        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                        Map<Long, ItemInventory> inventoryMap = inventoryClient.getInventorySnapshot(Long.valueOf(virtualWarehouseId));
                        List<Long> itemIds = new ArrayList<Long>();
                        File file = new File("/tmp/currentinventory.xls");
                        HSSFWorkbook hwb=new HSSFWorkbook();
                        HSSFSheet sheet =  hwb.createSheet("Inventory");
                        HSSFRow rowhead=   sheet.createRow((short)0);
                        rowhead.createCell((short) 0).setCellValue("item_id");
                        rowhead.createCell((short) 1).setCellValue("brand");
                        rowhead.createCell((short) 2).setCellValue("model_name");
                        rowhead.createCell((short) 3).setCellValue("model_number");
                        rowhead.createCell((short) 4).setCellValue("color");
                        rowhead.createCell((short) 5).setCellValue("Availability");
                        rowhead.createCell((short) 6).setCellValue("Reserved");
                        rowhead.createCell((short) 7).setCellValue("Held");

                        int iterator= 1;
                        for (Map.Entry<Long,ItemInventory> entry : inventoryMap.entrySet()) {
                                HSSFRow row = sheet.createRow((short)iterator);
                                itemIds.add(entry.getKey());
                                row.createCell((short) 0).setCellValue(entry.getKey());
                                row.createCell((short) 5).setCellValue(entry.getValue().getAvailability().get(Long.valueOf(virtualWarehouseId)));
                                row.createCell((short) 6).setCellValue(entry.getValue().getReserved().get(Long.valueOf(virtualWarehouseId)));
                                row.createCell((short) 7).setCellValue(entry.getValue().getHeld().get(Long.valueOf(virtualWarehouseId)));
                                iterator++;
                        }
                        Client cc = new CatalogClient().getClient();
                        Map<Long, Item> itemMap = cc.getItems(itemIds);
                        
                        iterator--;
                        Item d_item;
                        while(iterator!=0){
                                long item_id = (long) (sheet.getRow(iterator).getCell(0).getNumericCellValue());
                                d_item = itemMap.get(item_id);
                                if (d_item == null){
                                        iterator--;
                                        continue;
                                }
                                sheet.getRow(iterator).createCell((short) 1).setCellValue(d_item.getBrand());
                                sheet.getRow(iterator).createCell((short) 2).setCellValue(d_item.getModelName());
                                sheet.getRow(iterator).createCell((short) 3).setCellValue(d_item.getModelNumber());
                                sheet.getRow(iterator).createCell((short) 4).setCellValue(d_item.getColor());
                                iterator--;
                        }
                        
                        FileOutputStream fileOut = null;
                        try {
                                fileOut = new FileOutputStream(file);
                        } catch (FileNotFoundException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                        try {
                                hwb.write(fileOut);
                        } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                        try {
                                fileOut.close();
                        } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                        byte[] buffer = new byte[(int)file.length()];
                        InputStream input = null;
                        try {
                                int totalBytesRead = 0;
                                input = new BufferedInputStream(new FileInputStream(file));
                                while(totalBytesRead < buffer.length){
                                        int bytesRemaining = buffer.length - totalBytesRead;
                                        int bytesRead = input.read(buffer, totalBytesRead, bytesRemaining); 
                                        if (bytesRead > 0){
                                                totalBytesRead = totalBytesRead + bytesRead;
                                        }
                                }
                        }
                        finally {
                                input.close();
                                file.delete();
                        }

                        response.setHeader("Content-Disposition", "attachment; filename=\"Inventory.xls\"");
                        response.setContentType("application/octet-stream");
                        ServletOutputStream sos;
                        try {
                                sos = response.getOutputStream();
                                sos.write(buffer);
                                sos.flush();
                        } catch (IOException e) {
                                System.out.println("Unable to stream the manifest file");
                        }
                }
                catch(Exception e){
                        logger.error("Issue wile downloading virtual inventory"+e);
                        setResult("Something went wrong");
                        return "item-details-json";
                }
                setResult("Streaming done");
                return "item-details-json";
        }


        public boolean checkEmptyString(Cell cell){
                if (cell==null || cell.getCellType() == Cell.CELL_TYPE_BLANK){
                        return true;
                }
                return false;
        }

        public String getItemDetails(){
                return result;
        }

        public void setId(String id) {
                this.id = id;
        }

        public String getUserName(){
                return session.getAttribute(ReportsUtils.USER_NAME).toString();
        }

        public HttpServletRequest getRequest() {
                logger.info("set request"+request.toString());
                return request;
        }

        public void setRequest(HttpServletRequest request) {
                this.request = request;
        }

        public HttpServletResponse getResponse() {
                return response;
        }

        public void setResponse(HttpServletResponse response) {
                this.response = response;
        }

        public HttpSession getSession() {
                return session;
        }

        public void setSession(HttpSession session) {
                this.session = session;
        }

        public ServletContext getContext() {
                return context;
        }

        public void setContext(ServletContext context) {
                this.context = context;
        }


        public void setServletRequest(HttpServletRequest req) {
                this.request = req;
                this.session = req.getSession();        
        }

        public void setServletContext(ServletContext arg0) {
                // TODO Auto-generated method stub

        }

        public void setServletResponse(HttpServletResponse response) {
                this.response = response;
        }

        public String getResult() {
                return result;
        }

        public void setResult(String result) {
                this.result = result;
        }

        public File getFile() {
                return file;
        }

        public void setFile(File file) {
                this.file = file;
        }

        public static void main(String args[]) throws NumberFormatException, TException, IOException{
                BulkAddController b =  new BulkAddController();
                b.setVirtualWarehouseId("3295");
                b.downloadVirtualInventoryForWarehouse();
        }


}