Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
12449 kshitij.so 1
package in.shop2020.support.utils;
12355 vikram.rag 2
 
12449 kshitij.so 3
import in.shop2020.model.v1.catalog.AmazonPromotion;
12661 kshitij.so 4
import in.shop2020.model.v1.catalog.CatalogService.Client;
5
import in.shop2020.model.v1.catalog.CatalogServiceException;
6
import in.shop2020.model.v1.catalog.Item;
7
import in.shop2020.thrift.clients.CatalogClient;
8
import in.shop2020.utils.GmailUtils;
12449 kshitij.so 9
 
12355 vikram.rag 10
import java.io.BufferedReader;
11
import java.io.BufferedWriter;
12661 kshitij.so 12
import java.io.File;
12355 vikram.rag 13
import java.io.FileInputStream;
14
import java.io.FileNotFoundException;
15
import java.io.FileReader;
16
import java.io.FileWriter;
17
import java.io.IOException;
18
import java.security.DigestInputStream;
19
import java.security.MessageDigest;
20
import java.security.NoSuchAlgorithmException;
12661 kshitij.so 21
import java.util.ArrayList;
12355 vikram.rag 22
import java.util.Arrays;
12449 kshitij.so 23
import java.util.Calendar;
12661 kshitij.so 24
import java.util.GregorianCalendar;
12449 kshitij.so 25
import java.util.List;
12355 vikram.rag 26
 
27
import org.apache.commons.codec.binary.Base64;
12661 kshitij.so 28
import org.apache.thrift.TException;
29
import org.apache.thrift.transport.TTransportException;
30
import org.slf4j.Logger;
31
import org.slf4j.LoggerFactory;
12355 vikram.rag 32
 
33
import com.amazonaws.mws.MarketplaceWebService;
34
import com.amazonaws.mws.MarketplaceWebServiceClient;
35
import com.amazonaws.mws.MarketplaceWebServiceConfig;
36
import com.amazonaws.mws.MarketplaceWebServiceException;
37
import com.amazonaws.mws.model.IdList;
38
import com.amazonaws.mws.model.SubmitFeedRequest;
39
import com.amazonaws.mws.model.SubmitFeedResponse;
12449 kshitij.so 40
import com.ibm.icu.text.SimpleDateFormat;
12661 kshitij.so 41
import com.amazonaws.mws.samples.CheckPromoFeedSubmission;
12355 vikram.rag 42
 
12661 kshitij.so 43
public class PromotionFeed extends Thread{
44
 
45
    private static Logger logger = LoggerFactory.getLogger(PromotionFeed.class);
46
    private List<AmazonPromotion> amazonPromotions;
47
    public String[] sendTo = new String[]{ "rajneesh.arora@shop2020.in","kshitij.sood@shop2020.in","anikendra.das@shop2020.in",
48
            "khushal.bhatia@shop2020.in","manoj.kumar@saholic.com","chaitnaya.vats@saholic.com","chandan.kumar@shop2020.in"};
49
    //public String[] sendTo = new String[]{ "kshitij.sood@saholic.com"};
50
    public String emailFromAddress = "build-staging@shop2020.in";
51
    public String password = "shop2020";
52
    public String[] engineering = new String[]{ "eng@shop2020.in"};
53
 
54
    public PromotionFeed(List<AmazonPromotion> amazonPromotions){
55
        this.amazonPromotions = amazonPromotions;
56
    }
57
 
58
    void CreatePromotionFeed(List<AmazonPromotion> amazonPromotions) throws IOException, InterruptedException, MarketplaceWebServiceException{ 
59
        BufferedReader reader = null;
60
        BufferedWriter writer = null;
61
        String promotionFilename = null;
62
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
63
        Calendar calendar = Calendar.getInstance();
64
        try {
65
            promotionFilename = "/tmp/Promotion-"+System.currentTimeMillis()+".txt";
66
            reader = new BufferedReader(new FileReader("/temp-uploads/amazon-promo-flat-file.txt"));
67
            writer = new BufferedWriter(new FileWriter(promotionFilename));
68
            String Line;
69
            while ((Line = reader.readLine()) != null) {
70
                writer.write(Line+"\n");
71
            }
72
            for(AmazonPromotion am:amazonPromotions){
73
                calendar.setTimeInMillis(am.getStartDate());
74
                String start = formatter.format(calendar.getTime());
75
                calendar.setTimeInMillis(am.getEndDate());
12449 kshitij.so 76
                String end = formatter.format(calendar.getTime());
12661 kshitij.so 77
                writer.write(am.getSku()+"\t"+
78
                        ""+"\t"
79
                        +""+"\t"
80
                        +""+"\t"
81
                        +""+"\t"
82
                        +""+"\t"
83
                        +"\t"
84
                        +"\t"
85
                        +"\t"
86
                        +"\t"
87
                        +"PartialUpdate"+"\t"
88
                        +am.getStandardPrice()+"\t"
89
                        +""+"\t"	
90
                        +""+"\t"
91
                        +""+"\t"
92
                        +""+"\t"
93
                        +"1"+"\t"
94
                        +am.getSalePrice()+"\t"
95
                        +start+"\t"
96
                        +end+"\t"
97
                        +""+"\t"+"\n");
98
            }
12355 vikram.rag 99
 
12661 kshitij.so 100
        } catch (FileNotFoundException e1) {
101
            e1.printStackTrace();
102
        }
103
        finally{
104
            writer.close();
105
            reader.close();
106
        }
107
        try {
108
            SubmitPromotionFeed(promotionFilename,amazonPromotions);
12669 kshitij.so 109
        } catch (Exception e) {
12661 kshitij.so 110
            logger.error("TException in subit promtiono feed ",e);
111
            GmailUtils mailer = new GmailUtils();
112
            try{
113
                //mailer.sendSSLMessage(sendTo, "Amazon Promotion ( Submission Id " + feedSubmissionId + " )","", emailFromAddress , password, new ArrayList<File>(), tempFile);
114
                mailer.sendSSLMessage(engineering,"Thrift Exception in configuring amazon promotion",emailFromAddress, password, "");
115
            }
116
            catch(Exception ex){
117
                logger.info("Exception"+ex);
118
            }
119
        }
120
    }
121
 
122
    public void run(){
123
        try {
124
            this.CreatePromotionFeed(this.amazonPromotions);
125
        } catch (IOException e) {
126
            logger.error("IO exception while creating promo",e);
127
        } catch (InterruptedException e) {
128
            logger.error("IE exception while creating promo",e);
129
        } catch (MarketplaceWebServiceException e) {
130
            logger.error("MWS exception while creating promo",e);
131
        }
132
    }
133
 
12669 kshitij.so 134
    public void SubmitPromotionFeed(String file,List<AmazonPromotion> amazonPromotions) throws InterruptedException, MarketplaceWebServiceException, IOException, TException, CatalogServiceException{
12661 kshitij.so 135
        MarketplaceWebService service = getMarketplaceServiceInstance();
136
        SubmitFeedRequest requestPromotion = new SubmitFeedRequest();
137
        requestPromotion.setMerchant("AF6E3O0VE0X4D");
138
        requestPromotion.setMarketplaceIdList(new IdList(Arrays.asList("A21TJRUUN4KGV")));
139
        requestPromotion.setFeedType("_POST_FLAT_FILE_LISTINGS_DATA_");
140
        FileInputStream promotionfis = new FileInputStream(file);
141
        requestPromotion.setContentMD5(computeContentMD5HeaderValue(promotionfis));
142
        requestPromotion.setFeedContent(promotionfis);
143
        String feedSubmissionId = invokeSubmitFeed(service,requestPromotion);
12669 kshitij.so 144
        Thread.sleep(180000);
12661 kshitij.so 145
        sendPromotionConfigurationEmail(feedSubmissionId);
146
        CheckPromoFeedSubmission ck = new CheckPromoFeedSubmission();
147
        int checkResultCount=0;
148
        List<String> failedSkus=null;
149
        List<AmazonPromotion> successfulPromo = new ArrayList<AmazonPromotion>();
150
        while (failedSkus == null){
151
            failedSkus = ck.ProcessFeed(feedSubmissionId);
152
            if (failedSkus == null){
153
                checkResultCount++;
154
                if (checkResultCount == 7){
155
                    String text = "";
156
                    String[] sendTo = { "eng@shop2020.in" };
157
                    String emailSubjectTxt = "Unable To Receive Promo Feed Result.Submission Id "+feedSubmissionId;
158
                    String emailFromAddress = "build-staging@shop2020.in";
159
                    String password = "shop2020";
160
                    GmailUtils mailer = new GmailUtils();
161
                    try {
162
                        mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
163
                    }
164
                    catch (Exception e) {
165
                        e.printStackTrace();
166
                    }
167
                    return;
168
                }
169
                logger.info("=====Feed Result Not Ready Retry Again After 3 Minutes=============");
170
                Thread.sleep(180000);
171
            }
172
            else{
173
                for (AmazonPromotion am :amazonPromotions){
174
                    if (!failedSkus.contains(am.getSku())){
175
                        successfulPromo.add(am);
176
                    }
177
                }
178
                 Client catalogClient;
179
                 try {
180
                     catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
181
                 } catch (TTransportException e) {
182
                     logger.error("Catalog Service ex ",e);
183
                     return;
184
                 }
12669 kshitij.so 185
 
186
                 if(!catalogClient.updateAmazonPromotion(successfulPromo)){
187
                     throw new CatalogServiceException();
188
                 }
12661 kshitij.so 189
                 if (failedSkus.size()>0){
190
                     sendFailerMail(failedSkus,feedSubmissionId);
191
                 }
192
                 else{
193
                     sendSuccessMail(feedSubmissionId);
194
                 }
195
            }
196
        }
197
    }
198
 
199
    public void sendFailerMail(List<String> failedSkus,String feedSubmissionId){
200
        Client catalogClient;
201
        StringBuffer sb = new StringBuffer();
202
        sb.append("<html><table border=\"1\" align=\"center\">"
203
                + "<caption><b>" + "Amazon Promotion Failure" + "</b></caption>"
204
                + "<tr>" + "<td style=\"text-align:center;\"><b>" + "AMAZON-SKU" + "</b></td>" + 
205
                "<td style=\"text-align:center;\"><b>"
206
                + "PRODUCT-NAME" + "</b>"
207
                + "</tr>");
208
        try {
209
            catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
210
        } catch (TTransportException e) {
211
            logger.error("Catalog Service ex ",e);
212
            return;
213
        }
214
        GmailUtils mailer = new GmailUtils();
215
        for (String sku :failedSkus){
216
            Item item = null;
217
            try {
218
                item = catalogClient.getItem(Long.valueOf(sku.substring(3)));
219
            } catch (Exception e) {
220
                logger.error("Exception while parsing sku ",e);
221
                return;
222
            }
223
            sb.append("<tr>"+"<td style=\"text-align:center;\">"+sku+"</td>"
224
                    +"<td style=\"text-align:center;\">"+getVaildName(item.getBrand())+" "
225
                    +getVaildName(item.getModelName())+" "+getVaildName(item.getModelNumber())+" "+getVaildName(item.getColor())+"</td>"
226
                    +"</tr>"
227
            );
228
        }
229
        sb.append("</table></html>");
230
        //        String tempFile = "/tmp/"+getTimeInMilliseconds()+"-amazon-promo-mail.htm";
231
        //        BufferedWriter out = new BufferedWriter(new FileWriter(tempFile));
232
        //        out.write(sb.toString());
233
        //        out.flush();
234
        //        out.close();
235
        try{
236
            //mailer.sendSSLMessage(sendTo, "Amazon Promotion ( Submission Id " + feedSubmissionId + " )","", emailFromAddress , password, new ArrayList<File>(), tempFile);
237
            mailer.sendSSLMessage(sendTo,"Amazon Promotion ( Submission Id " + feedSubmissionId + " )",emailFromAddress, password, sb.toString());
238
        }
239
        catch(Exception e){
240
            logger.info("Exception"+e);
241
        }
242
    }
243
 
244
    public void sendPromotionConfigurationEmail(String feedSubmissionId) throws IOException{
245
        Client catalogClient;
246
        StringBuffer sb = new StringBuffer();
247
        sb.append("<html><table border=\"1\" align=\"center\">"
248
                + "<caption><b>" + "Amazon Promotion Details" + "</b></caption>"
249
                + "<tr>" + "<td style=\"text-align:center;\"><b>" + "AMAZON-SKU" + "</b></td>" + 
250
                "<td style=\"text-align:center;\"><b>"
251
                + "PRODUCT-NAME" + "</b></td>" + "<td style=\"text-align:center;\"><b>" + "STANDARD-PRICE"
252
                + "</b></td>" + "<td style=\"text-align:center;\"><b>" + "SALE-PRICE" + "</b></td>"
253
                + "<td style=\"text-align:center;\"><b>" + "SUBSIDY" + "</b></td>" + 
254
                "<td style=\"text-align:center;\"><b>"
255
                + "START-DATE" + "</b></td>" + "<td style=\"text-align:center;\"><b>" + "END-DATE"
256
                + "</tr>");
257
        try {
258
            catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
259
        } catch (TTransportException e) {
260
            logger.error("Catalog Service ex ",e);
261
            return;
262
        }
263
        GmailUtils mailer = new GmailUtils();
264
        for (AmazonPromotion amPromotion : this.amazonPromotions){
265
            Item item = null;
266
            try {
267
                item = catalogClient.getItem(Long.valueOf(amPromotion.getSku().substring(3)));
268
            } catch (Exception e) {
269
                logger.error("Exception while parsing sku ",e);
270
                return;
271
            }
272
            sb.append("<tr>"+"<td style=\"text-align:center;\">"+amPromotion.getSku()+"</td>"
273
                    +"<td style=\"text-align:center;\">"+getVaildName(item.getBrand())+" "
274
                    +getVaildName(item.getModelName())+" "+getVaildName(item.getModelNumber())+" "+getVaildName(item.getColor())+"</td>"
275
                    +"<td style=\"text-align:center;\">"+amPromotion.getStandardPrice()+"</td>"
276
                    +"<td style=\"text-align:center;\">"+amPromotion.getSalePrice()+"</td>"
277
                    +"<td style=\"text-align:center;\">"+amPromotion.getSubsidyAmount()+"</td>"
278
                    +"<td style=\"text-align:center;\">"+getDate(amPromotion.getStartDate())+"</td>"
279
                    +"<td style=\"text-align:center;\">"+getDate(amPromotion.getEndDate())+"</td>"+"</tr>"
280
            );
281
        }
282
        sb.append("</table></html>");
283
        //        String tempFile = "/tmp/"+getTimeInMilliseconds()+"-amazon-promo-mail.htm";
284
        //        BufferedWriter out = new BufferedWriter(new FileWriter(tempFile));
285
        //        out.write(sb.toString());
286
        //        out.flush();
287
        //        out.close();
288
        try{
289
            //mailer.sendSSLMessage(sendTo, "Amazon Promotion ( Submission Id " + feedSubmissionId + " )","", emailFromAddress , password, new ArrayList<File>(), tempFile);
290
            mailer.sendSSLMessage(sendTo,"Amazon Promotion ( Submission Id " + feedSubmissionId + " )",emailFromAddress, password, sb.toString());
291
        }
292
        catch(Exception e){
293
            logger.info("Exception"+e);
294
        }
295
    }
296
 
297
    public void sendSuccessMail(String feedSubmissionId){
298
        GmailUtils mailer = new GmailUtils();
299
        try{
300
            //mailer.sendSSLMessage(sendTo, "Amazon Promotion ( Submission Id " + feedSubmissionId + " )","", emailFromAddress , password, new ArrayList<File>(), tempFile);
301
            mailer.sendSSLMessage(sendTo,"Amazon Promotion Successfully configured( Submission Id " + feedSubmissionId + " )",emailFromAddress, password, "");
302
        }
303
        catch(Exception e){
304
            logger.info("Exception"+e);
305
        }
306
    }
307
 
308
    public String getVaildName(String name){
309
        return name!=null?name:"";
310
    }
311
 
312
    public String getDate(long timestamp){
313
        return new java.util.Date(timestamp).toLocaleString();
314
    }
315
 
316
    public String getTimeInMilliseconds(){
317
        Calendar cal=GregorianCalendar.getInstance();
318
        return String.valueOf(cal.getTimeInMillis());
319
    }
320
 
321
    public MarketplaceWebService getMarketplaceServiceInstance(){
322
        final String accessKeyId = "AKIAII3SGRXBJDPCHSGQ";
323
        final String secretAccessKey = "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";
324
        final String appName = "Test";
325
        final String appVersion = "1.0";
326
        MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();
327
        config.setServiceURL("https://mws.amazonservices.in");
328
        return new MarketplaceWebServiceClient(
329
                accessKeyId, secretAccessKey, appName, appVersion, config);
330
    }
331
 
332
    public static String computeContentMD5HeaderValue(FileInputStream fis) {
333
        try {
334
            DigestInputStream dis = new DigestInputStream(fis,
335
                    MessageDigest.getInstance("MD5"));
336
            byte[] buffer = new byte[8192];
337
            while (dis.read(buffer) > 0)
338
                ;
339
            String md5Content = new String(Base64.encodeBase64(dis
340
                    .getMessageDigest().digest()));
341
            // Effectively resets the stream to be beginning of the file via a
342
            fis.getChannel().position(0);
343
            return md5Content;
344
        } catch (NoSuchAlgorithmException e) {
345
            e.printStackTrace();
346
        } catch (IOException e) {
347
            e.printStackTrace();
348
        }
349
        return null;
350
    }
351
 
352
    public String invokeSubmitFeed(MarketplaceWebService service,SubmitFeedRequest request) throws InterruptedException, MarketplaceWebServiceException {
353
        SubmitFeedResponse response = service.submitFeed(request);
354
        return response.getSubmitFeedResult().getFeedSubmissionInfo().getFeedSubmissionId();
355
    }
356
 
357
}