Subversion Repositories SmartDukaan

Rev

Rev 12460 | Rev 12661 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.support.controllers;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import in.shop2020.model.v1.catalog.AmazonPromotionType;
import in.shop2020.model.v1.catalog.Amazonlisted;
import in.shop2020.model.v1.catalog.CatalogServiceException;
import in.shop2020.model.v1.catalog.Item;
import in.shop2020.model.v1.inventory.AmazonFbaInventorySnapshot;
import in.shop2020.model.v1.inventory.AmazonInventorySnapshot;
import in.shop2020.model.v1.catalog.AmazonPromotion;
import in.shop2020.model.v1.catalog.CatalogService.Client;
import in.shop2020.model.v1.inventory.InventoryServiceException;
import in.shop2020.model.v1.order.AmazonOrder;
import in.shop2020.support.utils.ReportsUtils;
import in.shop2020.support.utils.PromotionFeed;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.InventoryClient;
import in.shop2020.thrift.clients.LogisticsClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.logistics.DeliveryType;
import in.shop2020.logistics.LogisticsInfo;
import in.shop2020.logistics.LogisticsServiceException;
import in.shop2020.logistics.PickUpType;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.xwork.StringUtils;
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.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
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.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amazonaws.mws.MarketplaceWebServiceException;
import com.ibm.icu.text.SimpleDateFormat;
import com.opensymphony.xwork2.ValidationAwareSupport;

@SuppressWarnings("serial")

@InterceptorRefs({
    @InterceptorRef("defaultStack"),
    @InterceptorRef("login")
})
@Results({
    @Result(name = "redirect", location = "${url}", type = "redirect"),
    @Result(name="authsuccess", type="redirectAction", params = {"actionName" , "reports"})
})
public class AmazonListController extends ValidationAwareSupport implements ServletRequestAware ,ServletResponseAware, ServletContextAware{

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

    private HttpServletRequest request;
    private HttpSession session;
    private ServletContext context;
    private HttpServletResponse response;
    private String url;
    private String id;
    private String itemId;
    private String isFba;
    private String isNonFba;
    private String isInventoryOverride;
    private String fbaPrice;
    private String sellingPrice;
    private String saholicPrice;
    private String isTime;
    private String handlingTime;
    private String customHandlingTime;
    private String holdInventory;
    private String defaultInventory;
    private String fileUploadFileName;
    private String fileUploadContentType;
    private String suppressMfnPriceUpdate;
    private String suppressFbaPriceUpdate;
    private File file;
    private String errMsg;
    private String next;
    private List<Amazonlisted> amazonItems;
    private String searchText;
    private long searchCount;
    private long totalCount;
    private String taxCode;
    private String fbbTaxCode;
    private String isFbb;
    private String fbbPrice;
    private String suppressFbbPriceUpdate;
    private String startDate;
    private String endDate;
    private List<AmazonPromotion> promotionResult;
    private String promotionType;
    private String overrrideWanlc;
    private String exceptionalWanlc;
    private String autoDecrement;
    private String autoIncrement;
    private String autoFavourite;
    private String manualFavourite;
    private String otherCost;
    
    public String getOtherCost() {
        return otherCost;
    }

    public void setOtherCost(String otherCost) {
        this.otherCost = otherCost;
    }

    public String getAutoDecrement() {
        return autoDecrement;
    }

    public void setAutoDecrement(String autoDecrement) {
        this.autoDecrement = autoDecrement;
    }

    public String getAutoIncrement() {
        return autoIncrement;
    }

    public void setAutoIncrement(String autoIncrement) {
        this.autoIncrement = autoIncrement;
    }

    public String getAutoFavourite() {
        return autoFavourite;
    }

    public void setAutoFavourite(String autoFavourite) {
        this.autoFavourite = autoFavourite;
    }

    public String getManualFavourite() {
        return manualFavourite;
    }

    public void setManualFavourite(String manualFavourite) {
        this.manualFavourite = manualFavourite;
    }


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

    public String fetchItems() throws TException {
        Client CatalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
        if (searchText.length() == 0) {
            amazonItems = CatalogClient.getAmazonListedItems(Long.valueOf(next), 10);
            totalCount = CatalogClient.getCountForAmazonlistedItems();
            setSearchCount(totalCount);
        } else {
            List<String> subString = Arrays.asList(searchText.split(" "));
            amazonItems = CatalogClient.searchAmazonItems(subString,Long.valueOf(next), 10);
            totalCount = CatalogClient.getCountForAmazonlistedItems();
            searchCount = CatalogClient.getAmazonSearchResultCount(subString);
        }
        return "amazon-item-table";
    }


    public Amazonlisted fetchItemDetail() throws NumberFormatException, TException {
        Client CatalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
        return CatalogClient.getAmazonItemDetails(Long.valueOf(id));
    }

    public Item getSaholicItem(String id) throws NumberFormatException, CatalogServiceException, TException {
        Client CatalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
        return CatalogClient.getItem(Long.valueOf(id));
    }



    public String update() throws NumberFormatException, TException{
        Client CatalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
        boolean flag=false;
        boolean commit=false;
        long delay = Long.valueOf(customHandlingTime);
        if ( Boolean.valueOf(isTime)) {
            flag = true;
        }
        changeItemInventory();
        Amazonlisted amazonlisted = CatalogClient.getAmazonItemDetails(Long.valueOf(itemId));
        if (amazonlisted.getSellingPrice()!=Double.valueOf(sellingPrice)){
            amazonlisted.setSellingPrice(Double.valueOf(sellingPrice));
            commit=true;
        }
        if (amazonlisted.getFbaPrice()!=Double.valueOf(fbaPrice)){
            amazonlisted.setFbaPrice(Double.valueOf(fbaPrice));
            commit=true;
        }
        if (amazonlisted.isIsFba()!=Boolean.valueOf(isFba)){
            amazonlisted.setIsFba(Boolean.valueOf(isFba));
            commit=true;
        }
        if (amazonlisted.isIsNonFba()!=Boolean.valueOf(isNonFba)){
            amazonlisted.setIsNonFba(Boolean.valueOf(isNonFba));
            commit=true;
        }
        if (amazonlisted.isIsCustomTime()!=flag){
            amazonlisted.setIsCustomTime(flag);
            commit=true;
        }
        if (amazonlisted.getHandlingTime()!=delay){
            amazonlisted.setHandlingTime(delay);
            commit=true;
        }
        if(amazonlisted.isIsInventoryOverride()!=Boolean.valueOf(isInventoryOverride)){
            amazonlisted.setIsInventoryOverride(Boolean.valueOf(isInventoryOverride));
            commit=true;
        }
        if(amazonlisted.isSuppressMfnPriceUpdate()!=Boolean.valueOf(suppressMfnPriceUpdate)){
            amazonlisted.setSuppressMfnPriceUpdate(Boolean.valueOf(suppressMfnPriceUpdate));
            commit=true;
        }
        if(amazonlisted.isSuppressFbaPriceUpdate()!=Boolean.valueOf(suppressFbaPriceUpdate)){
            amazonlisted.setSuppressFbaPriceUpdate(Boolean.valueOf(suppressFbaPriceUpdate));
            commit=true;
        }

        if(!StringUtils.equals(amazonlisted.getTaxCode(), taxCode)){
            amazonlisted.setTaxCode(taxCode);
            commit=true;
        }

        if(!StringUtils.equals(amazonlisted.getFbbtaxCode(), fbbTaxCode)){
            amazonlisted.setFbbtaxCode(fbbTaxCode);
            commit=true;
        }

        if(amazonlisted.isSuppressFbbPriceUpdate()!=Boolean.valueOf(suppressFbbPriceUpdate)){
            amazonlisted.setSuppressFbbPriceUpdate(Boolean.valueOf(suppressFbbPriceUpdate));
            commit=true;
        }

        if (amazonlisted.getFbbPrice()!=Double.valueOf(fbbPrice)){
            amazonlisted.setFbbPrice(Double.valueOf(fbbPrice));
            commit=true;
        }

        if (amazonlisted.isIsFbb()!=Boolean.valueOf(isFbb)){
            amazonlisted.setIsFbb(Boolean.valueOf(isFbb));
            commit=true;
        }

        if (amazonlisted.isAutoDecrement()!=Boolean.valueOf(autoDecrement)){
            amazonlisted.setAutoDecrement(Boolean.valueOf(autoDecrement));
            commit=true;
        }
        
        if (amazonlisted.isAutoIncrement()!=Boolean.valueOf(autoIncrement)){
            amazonlisted.setAutoIncrement(Boolean.valueOf(autoIncrement));
            commit=true;
        }
        
        if (amazonlisted.isManualFavourite()!=Boolean.valueOf(manualFavourite)){
            amazonlisted.setManualFavourite(Boolean.valueOf(manualFavourite));
            commit=true;
        }


        if (amazonlisted.isOverrrideWanlc()!=Boolean.valueOf(overrrideWanlc)){
            amazonlisted.setOverrrideWanlc(Boolean.valueOf(overrrideWanlc));
            commit=true;
        }

        if (amazonlisted.getExceptionalWanlc()!=Double.valueOf(exceptionalWanlc)){
            amazonlisted.setExceptionalWanlc(Double.valueOf(exceptionalWanlc));
            commit=true;
        }
        
        if (amazonlisted.getOtherCost()!=Double.valueOf(otherCost)){
            amazonlisted.setOtherCost(Double.valueOf(otherCost));
            commit=true;
        }

        if(commit){
            CatalogClient.updateAmazonItemDetails(amazonlisted);
        }
        else{
            logger.info("Nothing new to commit");
        }
        return "index";

    }

    public void upload() throws IOException, TException {
        File fileToCreate = new File("/tmp/", "Amazon-shipping.xls");
        FileUtils.copyFile(this.file, fileToCreate);
        FileInputStream iFile = new FileInputStream(new File(file.getAbsolutePath()));
        HSSFWorkbook workbook = new HSSFWorkbook(iFile);
        HSSFSheet sheet = workbook.getSheetAt(0);
        Map<Long,Map<String,String>> amazonOrderMap = new HashMap<Long,Map<String,String>>();
        for (int iterator=sheet.getFirstRowNum();iterator<=sheet.getLastRowNum();iterator++){
            TransactionClient tcl = new TransactionClient();
            List<AmazonOrder> orders = tcl.getClient().getAmazonOrderByAmazonOrderId(sheet.getRow(iterator).getCell(0).getStringCellValue());
            for (AmazonOrder order : orders){
                if (StringUtils.equals(order.getStatus(), "Order-Payment-Success")){
                    Map<String,String> dateMap = new HashMap<String,String>();
                    dateMap.put(sheet.getRow(iterator).getCell(1).getStringCellValue(), sheet.getRow(iterator).getCell(2).getStringCellValue());
                    amazonOrderMap.put(order.getOrderId(), dateMap);
                }
            }
        }
        TransactionClient tcl = new TransactionClient();
        tcl.getClient().updateTimestampForAmazonOrder(amazonOrderMap);
    }

    public void uploadPromotionSheet() throws IOException, ParseException, TException, CatalogServiceException{
        Map<String,AmazonPromotion> amazonPromoMap = new HashMap<String,AmazonPromotion>();
        SimpleDateFormat dateFormatter;
        if (promotionType.equalsIgnoreCase("SHORTTERM")){
            dateFormatter = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
        }
        else{
            dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
        }
        File fileToCreate = new File("/tmp/", "Amazon-Promotion-"+String.valueOf(getTimeInMilliseconds())+".xls");
        FileUtils.copyFile(this.file, fileToCreate);
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file.getAbsolutePath()));
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        String str;
        int lineNumber = 0;
        while ((str = reader.readLine()) != null) {
            lineNumber++;
            if (str.trim().length() == 0 || lineNumber<2) {
                continue;
            }

            String[] values = str.split("\t");
            AmazonPromotion amazonPromotion = new AmazonPromotion();
            amazonPromotion.setSku(values[0]);
            amazonPromotion.setStandardPrice(Double.valueOf(values[1]));
            amazonPromotion.setSalePrice(Double.valueOf(values[2]));
            amazonPromotion.setSubsidyAmount(Double.valueOf(values[3]));
            Date startDate = dateFormatter.parse(values[4]);
            Date endDate = dateFormatter.parse(values[5]);
            amazonPromotion.setStartDate(startDate.getTime());
            amazonPromotion.setEndDate(endDate.getTime());
            amazonPromotion.setPromotionActive(true);
            amazonPromotion.setPromotionType(AmazonPromotionType.valueOf(promotionType));
            amazonPromoMap.put(amazonPromotion.getSku(), amazonPromotion);
        }
        Client cc = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
        if (!cc.addAmazonPromotion(amazonPromoMap)){
            throw new CatalogServiceException();
        }
//        if (promotionType.equalsIgnoreCase("LONGTERM")){
//            PromotionFeed pm = new PromotionFeed();
//            List<AmazonPromotion> list = new ArrayList<AmazonPromotion>(amazonPromoMap.values());
//            String fPath = pm.CreatePromotionFeed(list);
//            try {
//                logger.info(fPath);
//                pm.SubmitPromotionFeed(fPath);
//            } catch (InterruptedException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            } catch (MarketplaceWebServiceException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }
    }



    private void changeItemInventory() throws NumberFormatException, TException {
        Client CatalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();

        if (StringUtils.isEmpty(holdInventory)) {
            holdInventory = "0";
        }
        if (StringUtils.isEmpty(defaultInventory)) {
            defaultInventory = "0";
        }
        CatalogClient.updateItemInventory(Long.valueOf(itemId),Long.valueOf(holdInventory),Long.valueOf(defaultInventory));
    }


    public Map<Long, Long> getAvailableItemInventory(String itemId) throws NumberFormatException, InventoryServiceException, TException{
        InventoryClient inventoryServiceClient = new InventoryClient();
        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
        in.shop2020.model.v1.inventory.ItemInventory thriftItemInventory = inventoryClient.getItemInventoryByItemId(Long.valueOf(itemId));
        return thriftItemInventory.getAvailability();

    }

    public Map<Long, Long> getReservedItemInventory(String itemId) throws NumberFormatException, InventoryServiceException, TException{
        InventoryClient inventoryServiceClient = new InventoryClient();
        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
        in.shop2020.model.v1.inventory.ItemInventory thriftItemInventory = inventoryClient.getItemInventoryByItemId(Long.valueOf(itemId));
        return thriftItemInventory.getReserved();

    }

    public String getWarehouseName(String warehouseId) throws NumberFormatException, TException { 
        InventoryClient inventoryServiceClient = new InventoryClient();
        return inventoryServiceClient.getClient().getWarehouseName(Long.valueOf(warehouseId));
    }

    public AmazonInventorySnapshot getInventoryForAmazonItem(String itemId) throws NumberFormatException, TException {
        InventoryClient inventoryServiceClient = new InventoryClient();
        try { 
            return inventoryServiceClient.getClient().getAmazonInventoryForItem(Long.valueOf(itemId));
        }
        catch (Exception e){
            return null;
        }
    }

    public List<AmazonFbaInventorySnapshot> getFbaInventoryForAmazonItem(String itemId) throws NumberFormatException, TException {
        InventoryClient inventoryServiceClient = new InventoryClient();
        try { 
            return inventoryServiceClient.getClient().getAmazonFbaItemInventory(Long.valueOf(itemId));
        }
        catch (Exception e){
            return null;
        }
    }

    public Long getTimetoShip(String itemId) throws LogisticsServiceException, TException{
        LogisticsClient logisticsClient = new LogisticsClient();
        return logisticsClient.getClient().getLogisticsInfo("110001", Long.valueOf(itemId), DeliveryType.COD, PickUpType.COURIER).getShippingTime();
    }
    
//      public Long getTimetoShip(String itemId) throws LogisticsServiceException, TException{
//          return 0l;
//    }
    
    
    public double getWanlcForItem(String itemId){
        InventoryClient inventoryServiceClient;
        try {
            inventoryServiceClient = new InventoryClient();
        } catch (TTransportException e1) {
            // TODO Auto-generated catch block
            return 0.0;
        }
        try { 
            return inventoryServiceClient.getClient().getWanNlcForSource(Long.valueOf(itemId), 3);
        }
        catch (Exception e){
            return 0.0;
        }
    }

    public long getTimeInMilliseconds(){
        Calendar cal=GregorianCalendar.getInstance();
        return cal.getTimeInMillis();
    }

    public String runAsinJob() throws IOException, InterruptedException {
        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";
        }
        ProcessBuilder testProcess = new ProcessBuilder("/bin/bash");
        String[] command = {"/bin/bash", "-c", "sudo /root/code/trunk/AmazonFeeds/RunAsinJob.sh"};
        testProcess.command(command);
        logger.info(testProcess.command().toString());
        Process process = testProcess.start();
        process.waitFor();
        logger.info(String.valueOf(process.exitValue()));
        return "asinjob";

    }

    public String runFbbListingJob() throws IOException, InterruptedException {
        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";
        }
        ProcessBuilder testProcess = new ProcessBuilder("/bin/bash");
        String[] command = {"/bin/bash", "-c", "sudo /root/code/trunk/AmazonFeeds/RunFbbListingJob.sh"};
        testProcess.command(command);
        logger.info(testProcess.command().toString());
        Process process = testProcess.start();
        process.waitFor();
        logger.info(String.valueOf(process.exitValue()));
        return "asinjob";
    }


    public String runFbaListingJob() throws IOException, InterruptedException {
        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";
        }
        ProcessBuilder testProcess = new ProcessBuilder("/bin/bash");
        String[] command = {"/bin/bash", "-c", "sudo /root/code/trunk/AmazonFeeds/RunFbaListingJob.sh"};
        testProcess.command(command);
        logger.info(testProcess.command().toString());
        Process process = testProcess.start();
        process.waitFor();
        logger.info(String.valueOf(process.exitValue()));
        return "asinjob";
    }

    public String runNonFbaListingJob() throws IOException, InterruptedException {
        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";
        }
        ProcessBuilder testProcess = new ProcessBuilder("/bin/bash");
        String[] command = {"/bin/bash", "-c", "sudo /root/code/trunk/AmazonFeeds/RunNonFbaListingJob.sh"};
        testProcess.command(command);
        logger.info(testProcess.command().toString());
        Process process = testProcess.start();
        process.waitFor();
        logger.info(String.valueOf(process.exitValue()));
        return "asinjob";
    }

    public void runFbaInventoryJob() throws IOException, InterruptedException {
        ProcessBuilder testProcess = new ProcessBuilder("/bin/bash");
        String[] command = {"/bin/bash", "-c", "sudo /root/code/trunk/AmazonFeeds/SubmitFBAInventoryFeed.sh"};
        testProcess.command(command);
        logger.info(testProcess.command().toString());
        Process process = testProcess.start();
        process.waitFor();
        logger.info(String.valueOf(process.exitValue()));
    }

    public void uploadAsinFile() throws IOException, TException{
        File fileToCreate = new File("/tmp/", "Amazon-asin-upload.xls");
        FileUtils.copyFile(this.file, fileToCreate);
        FileInputStream iFile = new FileInputStream(new File(file.getAbsolutePath()));
        HSSFWorkbook workbook = new HSSFWorkbook(iFile);
        HSSFSheet sheet = workbook.getSheetAt(0);
        Map<Long,Item> amazonAsin = new HashMap<Long,Item>();
        StringBuilder sb =new StringBuilder();
        Client CatalogClient=null;
        try {
            CatalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
        } catch (TTransportException e) {
            e.printStackTrace();
        }
        for (int iterator=(sheet.getFirstRowNum()+1);iterator<=sheet.getLastRowNum();iterator++){
            Item item=null;
            Long sku;
            String asin;
            if (checkEmptyString(sheet.getRow(iterator).getCell(0))){
                continue;
            }
            else {
                sku=(long) sheet.getRow(iterator).getCell(0).getNumericCellValue();
                try {
                    item = CatalogClient.getItem(sku);
                } catch (Exception e) {
                    logger.info("Unable to fetch item details ID= "+sku);
                    logger.info("Unable to fetch item. "+e);
                    sb.append("Service exception ItemId not updated Id= "+sku+"\n");
                    continue;
                } 
            }

            if(item.getId() == 0){
                logger.info("Item Id doesn't exist in catalog Id= "+sku);
                sb.append("Item Id doesn't exist in catalog Id= "+sku+"\n");
                continue;
            }

            if (!checkEmptyString(sheet.getRow(iterator).getCell(1))){
                asin = sheet.getRow(iterator).getCell(1).getStringCellValue();
                item.setAsin(asin);
            }

            if (!checkEmptyString(sheet.getRow(iterator).getCell(2))){
                long virtualInventory =(long) sheet.getRow(iterator).getCell(2).getNumericCellValue();
                item.setDefaultInventory(virtualInventory);
            }

            if (!checkEmptyString(sheet.getRow(iterator).getCell(3))){
                long riskyInventory =(long) sheet.getRow(iterator).getCell(3).getNumericCellValue();
                item.setHoldInventory(riskyInventory);
            }

            amazonAsin.put(sku, item);
        }
        CatalogClient.updateAsin(amazonAsin);

        logger.info("Amazon Asin Map "+amazonAsin.toString());
        CatalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
        CatalogClient.updateAsin(amazonAsin);
        File file = new File("/tmp/asinfile");
        FileWriter writer = new FileWriter(file);
        writer.append(sb.toString());
        writer.close();
        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-Type", "text/javascript");

        ServletOutputStream sos;
        try {
            sos = response.getOutputStream();
            sos.write(buffer);
            sos.flush();
        } catch (IOException e) {
            System.out.println("Unable to stream the manifest file");
        }   
    }

    public void uploadBulkFile() throws IOException, TException{
        File fileToCreate = new File("/tmp/", "Amazon-bulk-upload.xls");
        FileUtils.copyFile(this.file, fileToCreate);
        FileInputStream iFile = new FileInputStream(new File(file.getAbsolutePath()));
        HSSFWorkbook workbook = new HSSFWorkbook(iFile);

        HSSFSheet sheet = workbook.getSheetAt(0);
        Map<Long,Amazonlisted> amazonBulkUpdate = new HashMap<Long,Amazonlisted>();
        Client CatalogClient=null;
        StringBuilder sb = new StringBuilder();
        try {
            CatalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
        } catch (TTransportException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        for (int iterator=(sheet.getFirstRowNum()+1);iterator<=sheet.getLastRowNum();iterator++){
            Amazonlisted amazonlisted =null;
            Long sku;
            if (checkEmptyString(sheet.getRow(iterator).getCell(0))){
                continue;
            }
            else {
                sku=(long) sheet.getRow(iterator).getCell(0).getNumericCellValue();
                try {
                    amazonlisted = CatalogClient.getAmazonItemDetails(sku);
                } catch (TException e) {
                    logger.info("Unable to fetch item details ID= "+sku);
                    sb.append("Service exception ItemId not updated Id= "+sku+"\n");
                    continue;
                }
            }

            if(amazonlisted.getItemid() == 0){
                logger.info("Item Id doesn't exist in amazonlisted Id= "+sku);
                sb.append("Item Id doesn't exist in amazonlisted Id= "+sku+"\n");
                continue;
            }

            if (!checkEmptyString(sheet.getRow(iterator).getCell(1))){
                double mfnPrice = sheet.getRow(iterator).getCell(1).getNumericCellValue();
                amazonlisted.setSellingPrice(mfnPrice);
            }

            if (!checkEmptyString(sheet.getRow(iterator).getCell(2))){
                double fbaSellingPrice = sheet.getRow(iterator).getCell(2).getNumericCellValue();
                amazonlisted.setFbaPrice(fbaSellingPrice);
            }

            if (!checkEmptyString(sheet.getRow(iterator).getCell(3))){
                double fbbSellingPrice = sheet.getRow(iterator).getCell(3).getNumericCellValue();
                amazonlisted.setFbbPrice(fbbSellingPrice);
            }

            if (!checkEmptyString(sheet.getRow(iterator).getCell(4))){
                if ((long)sheet.getRow(iterator).getCell(4).getNumericCellValue()==1){
                    amazonlisted.setIsNonFba(true);
                }
                if ((long)sheet.getRow(iterator).getCell(4).getNumericCellValue()==0){
                    amazonlisted.setIsNonFba(false);
                }
            }

            if (!checkEmptyString(sheet.getRow(iterator).getCell(5))){
                if ((long)sheet.getRow(iterator).getCell(5).getNumericCellValue()==1){
                    amazonlisted.setIsFba(true);
                }
                if ((long)sheet.getRow(iterator).getCell(5).getNumericCellValue()==0){
                    amazonlisted.setIsFba(false);
                }
            }

            if (!checkEmptyString(sheet.getRow(iterator).getCell(6))){
                if ((long)sheet.getRow(iterator).getCell(6).getNumericCellValue()==1){
                    amazonlisted.setIsFbb(true);
                }
                if ((long)sheet.getRow(iterator).getCell(6).getNumericCellValue()==0){
                    amazonlisted.setIsFbb(false);
                }
            }

            if (!checkEmptyString(sheet.getRow(iterator).getCell(7))){
                if ((long)sheet.getRow(iterator).getCell(7).getNumericCellValue()==1){
                    amazonlisted.setIsInventoryOverride(true);
                }
                if ((long)sheet.getRow(iterator).getCell(7).getNumericCellValue()==0){
                    amazonlisted.setIsInventoryOverride(false);
                }
            }
            if (!checkEmptyString(sheet.getRow(iterator).getCell(8))){
                if ((long)sheet.getRow(iterator).getCell(8).getNumericCellValue()==1){
                    amazonlisted.setSuppressMfnPriceUpdate(true);
                }
                if ((long)sheet.getRow(iterator).getCell(8).getNumericCellValue()==0){
                    amazonlisted.setSuppressMfnPriceUpdate(false);
                }
            }

            if (!checkEmptyString(sheet.getRow(iterator).getCell(9))){
                if ((long)sheet.getRow(iterator).getCell(9).getNumericCellValue()==1){
                    amazonlisted.setSuppressFbaPriceUpdate(true);
                }
                if ((long)sheet.getRow(iterator).getCell(9).getNumericCellValue()==0){
                    amazonlisted.setSuppressFbaPriceUpdate(false);
                }
            }

            if (!checkEmptyString(sheet.getRow(iterator).getCell(10))){
                if ((long)sheet.getRow(iterator).getCell(10).getNumericCellValue()==1){
                    amazonlisted.setSuppressFbbPriceUpdate(true);
                }
                if ((long)sheet.getRow(iterator).getCell(10).getNumericCellValue()==0){
                    amazonlisted.setSuppressFbbPriceUpdate(false);
                }
            }

            if (!checkEmptyString(sheet.getRow(iterator).getCell(11))){
                String taxCode = sheet.getRow(iterator).getCell(11).getStringCellValue();
                amazonlisted.setTaxCode(taxCode);
            }

            if (!checkEmptyString(sheet.getRow(iterator).getCell(12))){
                String fbbTaxCode = sheet.getRow(iterator).getCell(12).getStringCellValue();
                amazonlisted.setFbbtaxCode(fbbTaxCode);
            }
            
            if (!checkEmptyString(sheet.getRow(iterator).getCell(13))){
                double otherCost = sheet.getRow(iterator).getCell(13).getNumericCellValue();
                amazonlisted.setOtherCost(otherCost);
            }

            amazonBulkUpdate.put(sku, amazonlisted);
        }
        logger.info("Amazon Bulk Map "+amazonBulkUpdate.toString());
        CatalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
        boolean result = CatalogClient.updateAmazonAttributesInBulk(amazonBulkUpdate);
        if (!result){
            sb = new StringBuilder();
            sb.append("Error : Unable to update");
        }
        File file = new File("/tmp/amazonbulk");
        FileWriter writer = new FileWriter(file);
        writer.append(sb.toString());
        writer.close();
        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-Type", "text/javascript");

        ServletOutputStream sos;
        try {
            sos = response.getOutputStream();
            sos.write(buffer);
            sos.flush();
        } catch (IOException e) {
            System.out.println("Unable to stream the manifest file");
        }   
    }




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

    public String uploadSheet(){
        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 "amazon-shipping-upload";
    }

    public String uploadPromotion(){
        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 "amazon-promotion-upload";
    }

    public String uploadAsin(){
        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 "amazon-asin-upload";
    }

    public String uploadBulkSheet(){
        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 "amazon-bulk-upload";
    }


    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 viewPromotionDetails() throws ParseException, TException{
        logger.info(startDate);
        logger.info(endDate);
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
        Date start = dateFormatter.parse(startDate);
        Date end = dateFormatter.parse(endDate);
        logger.info(start.getTime()+"");
        logger.info(end.getTime()+"");
        Client cc = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
        setPromotionResult(cc.getAmazonPromotion(start.getTime(),end.getTime()));
        return "amazon-promotion-result";
    }

    public String getDate(long timestamp){
        return new java.util.Date(timestamp).toLocaleString();
    }

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

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

        if (StringUtils.equals(id, "item-table")){
            return "amazon-item-table";
        }

        if (StringUtils.equals(id, "promotion")){
            return "amazon-promotion";
        }

        return "id";
    }

    public String editNew() {
        return "editNew";
    }   

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

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUrl() {
        return url;
    }

    public String getId() {
        return id;
    }

    public void setItemId(String itemId) {
        this.itemId = itemId;
    }

    public String getItemId() {
        return itemId;
    }

    public void setIsFba(String isFba) {
        this.isFba = isFba;
    }

    public String getIsFba() {
        return isFba;
    }

    public void setIsNonFba(String isNonFba) {
        this.isNonFba = isNonFba;
    }

    public String getIsNonFba() {
        return isNonFba;
    }

    public void setIsInventoryOverride(String isInventoryOverride) {
        this.isInventoryOverride = isInventoryOverride;
    }

    public String getIsInventoryOverride() {
        return isInventoryOverride;
    }

    public void setSellingPrice(String sellingPrice) {
        this.sellingPrice = sellingPrice;
    }

    public String getSellingPrice() {
        return sellingPrice;
    }

    public void setFbaPrice(String fbaPrice) {
        this.fbaPrice = fbaPrice;
    }

    public String getFbaPrice() {
        return fbaPrice;
    }

    public void setSaholicPrice(String saholicPrice) {
        this.saholicPrice = saholicPrice;
    }

    public String getSaholicPrice() {
        return saholicPrice;
    }

    public void setIsTime(String isTime){
        logger.info("set istime"+isTime);
        this.isTime = isTime;
    }

    public String getIsTime(){
        return isTime;
    }

    public void setHandlingTime(String handlingTime){
        this.handlingTime = handlingTime;
    }

    public String getHandlingTime(){
        return handlingTime;
    }

    public void setCustomHandlingTime(String customHandlingTime){
        logger.info("set custom handling time"+customHandlingTime);
        this.customHandlingTime = customHandlingTime;
    }

    public String getCustomHandlingTime(){
        return customHandlingTime;
    }

    public void setHoldInventory(String holdInventory){
        this.holdInventory = holdInventory;
    }

    public String getHoldInventory(){
        return holdInventory;
    }

    public void setDefaultInventory(String defaultInventory){
        this.defaultInventory = defaultInventory;
    }

    public String getDefaultInventory(){
        return defaultInventory;
    }

    public File getFile() {
        return file;
    }

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

    public String getFileUploadContentType() {
        return fileUploadContentType;
    }

    public void setFileUploadContentType(String fileUploadContentType) {
        this.fileUploadContentType = fileUploadContentType;
    }

    public String getFileUploadFileName() {
        return fileUploadFileName;
    }

    public void setFileUploadFileName(String fileUploadFileName) {
        this.fileUploadFileName = fileUploadFileName;
    }

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

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

    }


    public void setSuppressMfnPriceUpdate(String suppressMfnPriceUpdate) {
        this.suppressMfnPriceUpdate = suppressMfnPriceUpdate;
    }

    public String getSuppressMfnPriceUpdate() {
        return suppressMfnPriceUpdate;
    }

    public void setSuppressFbaPriceUpdate(String suppressFbaPriceUpdate) {
        this.suppressFbaPriceUpdate = suppressFbaPriceUpdate;
    }

    public String getSuppressFbaPriceUpdate() {
        return suppressFbaPriceUpdate;
    }

    public void setErrMsg(String errMsg) {
        this.errMsg = errMsg;
    }

    public String getErrMsg() {
        return errMsg;
    }

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

    public void setNext(String next) {
        logger.info("next is"+next);
        this.next = next;
    }

    public String getNext() {
        return next;
    }

    public void setAmazonItems(List<Amazonlisted> amazonItems) {
        this.amazonItems = amazonItems;
    }

    public List<Amazonlisted> getAmazonItems() {
        return amazonItems;
    }

    public void setSearchText(String searchText) {
        this.searchText = searchText;
    }

    public String getSearchText() {
        return searchText;
    }

    public long getSearchCount() {
        return searchCount;
    }

    public long getTotalCount() {
        return totalCount;
    }

    public void setSearchCount(long count) {
        this.searchCount = count;
    }

    public void setTaxCode(String taxCode) {
        this.taxCode = taxCode;
    }

    public String getTaxCode() {
        return taxCode;
    }

    public void setFbbTaxCode(String fbbTaxCode) {
        this.fbbTaxCode = fbbTaxCode;
    }

    public String get() {
        return fbbTaxCode;
    }

    public void setIsFbb(String isFbb) {
        this.isFbb = isFbb;
    }

    public String getIsFbb() {
        return isFbb;
    }

    public void setFbbPrice(String fbbPrice) {
        this.fbbPrice = fbbPrice;
    }

    public String getFbbPrice() {
        return fbbPrice;
    }

    public void setSuppressFbbPriceUpdate(String suppressFbbPriceUpdate) {
        this.suppressFbbPriceUpdate = suppressFbbPriceUpdate;
    }

    public String getSuppressFbbPriceUpdate() {
        return suppressFbbPriceUpdate;
    }

    public String getStartDate() {
        return startDate;
    }

    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }

    public String getEndDate() {
        return endDate;
    }

    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }

    public void setPromotionResult(List<AmazonPromotion> promotionResult) {
        this.promotionResult = promotionResult;
    }

    public List<AmazonPromotion> getPromotionResult() {
        return promotionResult;
    }

    public String getPromotionType() {
        return promotionType;
    }

    public void setPromotionType(String promotionType) {
        this.promotionType = promotionType;
    }

    public String getOverrrideWanlc() {
        return overrrideWanlc;
    }

    public void setOverrrideWanlc(String overrrideWanlc) {
        this.overrrideWanlc = overrrideWanlc;
    }

    public String getExceptionalWanlc() {
        return exceptionalWanlc;
    }

    public void setExceptionalWanlc(String exceptionalWanlc) {
        this.exceptionalWanlc = exceptionalWanlc;
    }

}