Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.support.utils;

import in.shop2020.model.v1.catalog.AmazonPromotion;
import in.shop2020.model.v1.catalog.CatalogService.Client;
import in.shop2020.model.v1.catalog.CatalogServiceException;
import in.shop2020.model.v1.catalog.Item;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.utils.GmailUtils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
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.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amazonaws.mws.MarketplaceWebService;
import com.amazonaws.mws.MarketplaceWebServiceClient;
import com.amazonaws.mws.MarketplaceWebServiceConfig;
import com.amazonaws.mws.MarketplaceWebServiceException;
import com.amazonaws.mws.model.IdList;
import com.amazonaws.mws.model.SubmitFeedRequest;
import com.amazonaws.mws.model.SubmitFeedResponse;
import com.ibm.icu.text.SimpleDateFormat;
import com.amazonaws.mws.samples.CheckPromoFeedSubmission;

public class PromotionFeed extends Thread{

    private static Logger logger = LoggerFactory.getLogger(PromotionFeed.class);
    private List<AmazonPromotion> amazonPromotions;
    public String[] sendTo = new String[]{ "rajneesh.arora@shop2020.in","kshitij.sood@shop2020.in","anikendra.das@shop2020.in",
            "khushal.bhatia@shop2020.in","manoj.kumar@saholic.com","chaitnaya.vats@saholic.com","chandan.kumar@shop2020.in"};
    //public String[] sendTo = new String[]{ "kshitij.sood@saholic.com"};
    public String emailFromAddress = "build-staging@shop2020.in";
    public String password = "shop2020";
    public String[] engineering = new String[]{ "eng@shop2020.in"};

    public PromotionFeed(List<AmazonPromotion> amazonPromotions){
        this.amazonPromotions = amazonPromotions;
    }

    void CreatePromotionFeed(List<AmazonPromotion> amazonPromotions) throws IOException, InterruptedException, MarketplaceWebServiceException{ 
        BufferedReader reader = null;
        BufferedWriter writer = null;
        String promotionFilename = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        try {
            promotionFilename = "/tmp/Promotion-"+System.currentTimeMillis()+".txt";
            reader = new BufferedReader(new FileReader("/temp-uploads/amazon-promo-flat-file.txt"));
            writer = new BufferedWriter(new FileWriter(promotionFilename));
            String Line;
            while ((Line = reader.readLine()) != null) {
                writer.write(Line+"\n");
            }
            for(AmazonPromotion am:amazonPromotions){
                calendar.setTimeInMillis(am.getStartDate());
                String start = formatter.format(calendar.getTime());
                calendar.setTimeInMillis(am.getEndDate());
                String end = formatter.format(calendar.getTime());
                writer.write(am.getSku()+"\t"+
                        ""+"\t"
                        +""+"\t"
                        +""+"\t"
                        +""+"\t"
                        +""+"\t"
                        +"\t"
                        +"\t"
                        +"\t"
                        +"\t"
                        +"PartialUpdate"+"\t"
                        +am.getStandardPrice()+"\t"
                        +""+"\t"        
                        +""+"\t"
                        +""+"\t"
                        +""+"\t"
                        +"1"+"\t"
                        +am.getSalePrice()+"\t"
                        +start+"\t"
                        +end+"\t"
                        +""+"\t"+"\n");
            }

        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        finally{
            writer.close();
            reader.close();
        }
        try {
            SubmitPromotionFeed(promotionFilename,amazonPromotions);
        } catch (Exception e) {
            logger.error("TException in subit promtiono feed ",e);
            GmailUtils mailer = new GmailUtils();
            try{
                //mailer.sendSSLMessage(sendTo, "Amazon Promotion ( Submission Id " + feedSubmissionId + " )","", emailFromAddress , password, new ArrayList<File>(), tempFile);
                mailer.sendSSLMessage(engineering,"Thrift Exception in configuring amazon promotion",emailFromAddress, password, "");
            }
            catch(Exception ex){
                logger.info("Exception"+ex);
            }
        }
    }

    public void run(){
        try {
            this.CreatePromotionFeed(this.amazonPromotions);
        } catch (IOException e) {
            logger.error("IO exception while creating promo",e);
        } catch (InterruptedException e) {
            logger.error("IE exception while creating promo",e);
        } catch (MarketplaceWebServiceException e) {
            logger.error("MWS exception while creating promo",e);
        }
    }

    public void SubmitPromotionFeed(String file,List<AmazonPromotion> amazonPromotions) throws InterruptedException, MarketplaceWebServiceException, IOException, TException, CatalogServiceException{
        MarketplaceWebService service = getMarketplaceServiceInstance();
        SubmitFeedRequest requestPromotion = new SubmitFeedRequest();
        requestPromotion.setMerchant("AF6E3O0VE0X4D");
        requestPromotion.setMarketplaceIdList(new IdList(Arrays.asList("A21TJRUUN4KGV")));
        requestPromotion.setFeedType("_POST_FLAT_FILE_LISTINGS_DATA_");
        FileInputStream promotionfis = new FileInputStream(file);
        requestPromotion.setContentMD5(computeContentMD5HeaderValue(promotionfis));
        requestPromotion.setFeedContent(promotionfis);
        String feedSubmissionId = invokeSubmitFeed(service,requestPromotion);
        Thread.sleep(180000);
        sendPromotionConfigurationEmail(feedSubmissionId);
        CheckPromoFeedSubmission ck = new CheckPromoFeedSubmission();
        int checkResultCount=0;
        List<String> failedSkus=null;
        List<AmazonPromotion> successfulPromo = new ArrayList<AmazonPromotion>();
        while (failedSkus == null){
            failedSkus = ck.ProcessFeed(feedSubmissionId);
            if (failedSkus == null){
                checkResultCount++;
                if (checkResultCount == 7){
                    String text = "";
                    String[] sendTo = { "eng@shop2020.in" };
                    String emailSubjectTxt = "Unable To Receive Promo Feed Result.Submission Id "+feedSubmissionId;
                    String emailFromAddress = "build-staging@shop2020.in";
                    String password = "shop2020";
                    GmailUtils mailer = new GmailUtils();
                    try {
                        mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                    return;
                }
                logger.info("=====Feed Result Not Ready Retry Again After 3 Minutes=============");
                Thread.sleep(180000);
            }
            else{
                for (AmazonPromotion am :amazonPromotions){
                    if (!failedSkus.contains(am.getSku())){
                        successfulPromo.add(am);
                    }
                }
                 Client catalogClient;
                 try {
                     catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
                 } catch (TTransportException e) {
                     logger.error("Catalog Service ex ",e);
                     return;
                 }
                 
                 if(!catalogClient.updateAmazonPromotion(successfulPromo)){
                     throw new CatalogServiceException();
                 }
                 if (failedSkus.size()>0){
                     sendFailerMail(failedSkus,feedSubmissionId);
                 }
                 else{
                     sendSuccessMail(feedSubmissionId);
                 }
            }
        }
    }
    
    public void sendFailerMail(List<String> failedSkus,String feedSubmissionId){
        Client catalogClient;
        StringBuffer sb = new StringBuffer();
        sb.append("<html><table border=\"1\" align=\"center\">"
                + "<caption><b>" + "Amazon Promotion Failure" + "</b></caption>"
                + "<tr>" + "<td style=\"text-align:center;\"><b>" + "AMAZON-SKU" + "</b></td>" + 
                "<td style=\"text-align:center;\"><b>"
                + "PRODUCT-NAME" + "</b>"
                + "</tr>");
        try {
            catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
        } catch (TTransportException e) {
            logger.error("Catalog Service ex ",e);
            return;
        }
        GmailUtils mailer = new GmailUtils();
        for (String sku :failedSkus){
            Item item = null;
            try {
                item = catalogClient.getItem(Long.valueOf(sku.substring(3)));
            } catch (Exception e) {
                logger.error("Exception while parsing sku ",e);
                return;
            }
            sb.append("<tr>"+"<td style=\"text-align:center;\">"+sku+"</td>"
                    +"<td style=\"text-align:center;\">"+getVaildName(item.getBrand())+" "
                    +getVaildName(item.getModelName())+" "+getVaildName(item.getModelNumber())+" "+getVaildName(item.getColor())+"</td>"
                    +"</tr>"
            );
        }
        sb.append("</table></html>");
        //        String tempFile = "/tmp/"+getTimeInMilliseconds()+"-amazon-promo-mail.htm";
        //        BufferedWriter out = new BufferedWriter(new FileWriter(tempFile));
        //        out.write(sb.toString());
        //        out.flush();
        //        out.close();
        try{
            //mailer.sendSSLMessage(sendTo, "Amazon Promotion ( Submission Id " + feedSubmissionId + " )","", emailFromAddress , password, new ArrayList<File>(), tempFile);
            mailer.sendSSLMessage(sendTo,"Amazon Promotion ( Submission Id " + feedSubmissionId + " )",emailFromAddress, password, sb.toString());
        }
        catch(Exception e){
            logger.info("Exception"+e);
        }
    }

    public void sendPromotionConfigurationEmail(String feedSubmissionId) throws IOException{
        Client catalogClient;
        StringBuffer sb = new StringBuffer();
        sb.append("<html><table border=\"1\" align=\"center\">"
                + "<caption><b>" + "Amazon Promotion Details" + "</b></caption>"
                + "<tr>" + "<td style=\"text-align:center;\"><b>" + "AMAZON-SKU" + "</b></td>" + 
                "<td style=\"text-align:center;\"><b>"
                + "PRODUCT-NAME" + "</b></td>" + "<td style=\"text-align:center;\"><b>" + "STANDARD-PRICE"
                + "</b></td>" + "<td style=\"text-align:center;\"><b>" + "SALE-PRICE" + "</b></td>"
                + "<td style=\"text-align:center;\"><b>" + "SUBSIDY" + "</b></td>" + 
                "<td style=\"text-align:center;\"><b>"
                + "START-DATE" + "</b></td>" + "<td style=\"text-align:center;\"><b>" + "END-DATE"
                + "</tr>");
        try {
            catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
        } catch (TTransportException e) {
            logger.error("Catalog Service ex ",e);
            return;
        }
        GmailUtils mailer = new GmailUtils();
        for (AmazonPromotion amPromotion : this.amazonPromotions){
            Item item = null;
            try {
                item = catalogClient.getItem(Long.valueOf(amPromotion.getSku().substring(3)));
            } catch (Exception e) {
                logger.error("Exception while parsing sku ",e);
                return;
            }
            sb.append("<tr>"+"<td style=\"text-align:center;\">"+amPromotion.getSku()+"</td>"
                    +"<td style=\"text-align:center;\">"+getVaildName(item.getBrand())+" "
                    +getVaildName(item.getModelName())+" "+getVaildName(item.getModelNumber())+" "+getVaildName(item.getColor())+"</td>"
                    +"<td style=\"text-align:center;\">"+amPromotion.getStandardPrice()+"</td>"
                    +"<td style=\"text-align:center;\">"+amPromotion.getSalePrice()+"</td>"
                    +"<td style=\"text-align:center;\">"+amPromotion.getSubsidyAmount()+"</td>"
                    +"<td style=\"text-align:center;\">"+getDate(amPromotion.getStartDate())+"</td>"
                    +"<td style=\"text-align:center;\">"+getDate(amPromotion.getEndDate())+"</td>"+"</tr>"
            );
        }
        sb.append("</table></html>");
        //        String tempFile = "/tmp/"+getTimeInMilliseconds()+"-amazon-promo-mail.htm";
        //        BufferedWriter out = new BufferedWriter(new FileWriter(tempFile));
        //        out.write(sb.toString());
        //        out.flush();
        //        out.close();
        try{
            //mailer.sendSSLMessage(sendTo, "Amazon Promotion ( Submission Id " + feedSubmissionId + " )","", emailFromAddress , password, new ArrayList<File>(), tempFile);
            mailer.sendSSLMessage(sendTo,"Amazon Promotion ( Submission Id " + feedSubmissionId + " )",emailFromAddress, password, sb.toString());
        }
        catch(Exception e){
            logger.info("Exception"+e);
        }
    }
    
    public void sendSuccessMail(String feedSubmissionId){
        GmailUtils mailer = new GmailUtils();
        try{
            //mailer.sendSSLMessage(sendTo, "Amazon Promotion ( Submission Id " + feedSubmissionId + " )","", emailFromAddress , password, new ArrayList<File>(), tempFile);
            mailer.sendSSLMessage(sendTo,"Amazon Promotion Successfully configured( Submission Id " + feedSubmissionId + " )",emailFromAddress, password, "");
        }
        catch(Exception e){
            logger.info("Exception"+e);
        }
    }

    public String getVaildName(String name){
        return name!=null?name:"";
    }

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

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

    public MarketplaceWebService getMarketplaceServiceInstance(){
        final String accessKeyId = "AKIAII3SGRXBJDPCHSGQ";
        final String secretAccessKey = "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";
        final String appName = "Test";
        final String appVersion = "1.0";
        MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();
        config.setServiceURL("https://mws.amazonservices.in");
        return new MarketplaceWebServiceClient(
                accessKeyId, secretAccessKey, appName, appVersion, config);
    }

    public static String computeContentMD5HeaderValue(FileInputStream fis) {
        try {
            DigestInputStream dis = new DigestInputStream(fis,
                    MessageDigest.getInstance("MD5"));
            byte[] buffer = new byte[8192];
            while (dis.read(buffer) > 0)
                ;
            String md5Content = new String(Base64.encodeBase64(dis
                    .getMessageDigest().digest()));
            // Effectively resets the stream to be beginning of the file via a
            fis.getChannel().position(0);
            return md5Content;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String invokeSubmitFeed(MarketplaceWebService service,SubmitFeedRequest request) throws InterruptedException, MarketplaceWebServiceException {
        SubmitFeedResponse response = service.submitFeed(request);
        return response.getSubmitFeedResult().getFeedSubmissionInfo().getFeedSubmissionId();
    }

}