Subversion Repositories SmartDukaan

Rev

Rev 12661 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
12459 kshitij.so 1
/*******************************************************************************
2
 *  Copyright 2009 Amazon Services.
3
 *  Licensed under the Apache License, Version 2.0 (the "License"); 
4
 *  
5
 *  You may not use this file except in compliance with the License. 
6
 *  You may obtain a copy of the License at: http://aws.amazon.com/apache2.0
7
 *  This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
8
 *  CONDITIONS OF ANY KIND, either express or implied. See the License for the 
9
 *  specific language governing permissions and limitations under the License.
10
 * ***************************************************************************** 
11
 *
12
 *  Marketplace Web Service Java Library
13
 *  API Version: 2009-01-01
14
 *  Generated: Wed Feb 18 13:28:48 PST 2009 
15
 * 
16
 */
17
 
18
package com.amazonaws.mws.samples;
19
 
20
import java.io.ByteArrayInputStream;
21
import in.shop2020.model.v1.catalog.Amazonlisted;
22
import java.io.File;
23
import java.io.FileInputStream;
24
import java.io.FileNotFoundException;
25
import java.io.IOException;
26
import java.io.PrintWriter;
27
import java.io.StringWriter;
28
import java.math.BigDecimal;
29
import java.math.BigInteger;
30
import java.nio.channels.FileChannel;
31
import java.security.DigestInputStream;
32
import java.security.MessageDigest;
33
import java.security.NoSuchAlgorithmException;
34
import java.util.Arrays;
35
import java.util.Calendar;
36
import java.util.Date;
37
import java.util.GregorianCalendar;
38
import java.util.HashMap;
39
import java.util.Iterator;
40
import java.util.List;
41
import java.util.ArrayList;
42
import java.util.Map;
43
import java.util.Random;
44
import java.util.TimeZone;
45
 
46
import javax.xml.bind.JAXBContext;
47
import javax.xml.bind.JAXBException;
48
import javax.xml.bind.Marshaller;
49
import javax.xml.datatype.DatatypeConfigurationException;
50
import javax.xml.datatype.DatatypeConstants;
51
import javax.xml.datatype.DatatypeFactory;
52
import javax.xml.datatype.XMLGregorianCalendar;
53
import javax.xml.parsers.ParserConfigurationException;
54
 
55
import com.amazonaws.mws.*;
56
import com.amazonaws.mws.model.*;
57
import com.amazonaws.mws.samples.ProcessFeed;
58
import com.amazonaws.mws.samples.CheckFeedSubmission;
59
import com.amazonaws.mws.mock.MarketplaceWebServiceMock;
60
import org.apache.commons.codec.binary.*;
61
 
62
import in.shop2020.feeds.products.AmazonEnvelope;
63
import in.shop2020.feeds.products.BaseCurrencyCodeWithDefault;
64
import in.shop2020.feeds.products.CE;
65
import in.shop2020.feeds.products.HandheldOrPDA;
66
import in.shop2020.feeds.products.Header;
67
import in.shop2020.feeds.products.Inventory;
68
import in.shop2020.feeds.products.Listings;
69
import in.shop2020.feeds.products.OverrideCurrencyAmount;
70
import in.shop2020.feeds.products.Price;
71
import in.shop2020.feeds.products.Product;
72
import in.shop2020.feeds.products.StandardProductID;
73
import in.shop2020.model.v1.catalog.CatalogService.Client;
74
import in.shop2020.model.v1.catalog.CatalogServiceException;
75
import in.shop2020.model.v1.catalog.Item;
76
import in.shop2020.model.v1.inventory.InventoryServiceException;
77
import in.shop2020.model.v1.inventory.ItemInventory;
78
import in.shop2020.thrift.clients.CatalogClient;
79
import in.shop2020.thrift.clients.InventoryClient;
80
import in.shop2020.thrift.clients.WarehouseClient;
81
import in.shop2020.utils.GmailUtils;
82
 
83
import org.apache.thrift.TException;
84
import org.apache.thrift.transport.TTransportException;
85
import org.xml.sax.SAXException;
86
 
87
/**
88
 * 
89
 * Submit Feed Samples
90
 * 
91
 * 
92
 */
93
public class SubmitFBAPricingFeedAndFetchResults {
94
 
95
	/**
96
	 * Just add a few required parameters, and try the service Submit Feed
97
	 * functionality
98
	 * 
99
	 * @param args
100
	 *            unused
101
	 *            
102
	 */
103
	/**
104
	 * @param args
105
	 * @throws TException 
106
	 * @throws CatalogServiceException 
107
	 */
108
 
109
	static java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
110
	static Calendar cal=GregorianCalendar.getInstance();
111
	final public static String AMAZON_FBA_PRICING_XML   = "/home/amazon/Fbapricing"+sdf.format(cal.getTime())+".xml";
112
	final public static boolean PURGE_OR_REPLACE   = false;
113
	static long milliseconds;
114
	public static  List<Amazonlisted> aItems=null;
115
	public static List<Long> itemIdsToUpdate=null;
116
 
117
	static{
118
 
119
		CatalogClient catalogServiceClient = null;
120
		try {
121
			catalogServiceClient = new CatalogClient();
122
		} catch (TTransportException e) {
123
			// TODO Auto-generated catch block
124
			e.printStackTrace();
125
		}
126
		Client catalogClient = catalogServiceClient.getClient();
127
		try {
128
			Calendar cal=GregorianCalendar.getInstance();
129
			milliseconds = cal.getTimeInMillis();
130
			aItems = catalogClient.getAllFbaListedItems();
131
 
132
		} catch (TException e) {
133
			// TODO Auto-generated catch block
134
			e.printStackTrace();
135
		}
136
 
137
	}
138
	public static void main(String... args) throws CatalogServiceException, TException {
139
 
140
		/**************************************************	**********************
141
		 * Access Key ID and Secret Access Key ID, obtained from:
142
		 * http://aws.amazon.com
143
		 ***********************************************************************/
144
 
145
 
146
		//public static final String marketplaceId = "A21TJRUUN4KGV";
147
 
148
 
149
 
150
 
151
		final String accessKeyId = "AKIAII3SGRXBJDPCHSGQ";
152
		final String secretAccessKey = "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";
153
 
154
		final String appName = "Test";
155
		final String appVersion = "1.0";
156
 
157
		MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();
158
 
159
		/************************************************************************
160
		 * Uncomment to set the appropriate MWS endpoint.
161
		 ************************************************************************/
162
		// US
163
		// config.setServiceURL("https://mws.amazonservices.com");
164
		// UK
165
		// config.setServiceURL("https://mws.amazonservices.co.uk");
166
		// Germany
167
		// config.setServiceURL("https://mws.amazonservices.de");
168
		// France
169
		// config.setServiceURL("https://mws.amazonservices.fr");
170
		// Italy
171
		// config.setServiceURL("https://mws.amazonservices.it");
172
		// Japan
173
		// config.setServiceURL("https://mws.amazonservices.jp");
174
		// China
175
		// config.setServiceURL("https://mws.amazonservices.com.cn");
176
		// Canada
177
		// config.setServiceURL("https://mws.amazonservices.ca");
178
		// India
179
		config.setServiceURL("https://mws.amazonservices.in");
180
 
181
 
182
		/************************************************************************
183
		 * You can also try advanced configuration options. Available options are:
184
		 *
185
		 *  - Signature Version
186
		 *  - Proxy Host and Proxy Port
187
		 *  - User Agent String to be sent to Marketplace Web Service
188
		 *
189
		 ***********************************************************************/
190
 
191
		/************************************************************************
192
		 * Instantiate Http Client Implementation of Marketplace Web Service        
193
		 ***********************************************************************/
194
 
195
		MarketplaceWebService service = new MarketplaceWebServiceClient(
196
				accessKeyId, secretAccessKey, appName, appVersion, config);
197
 
198
 
199
		/************************************************************************
200
		 * Setup request parameters and uncomment invoke to try out sample for
201
		 * Submit Feed
202
		 ***********************************************************************/
203
 
204
		/************************************************************************
205
		 * Marketplace and Merchant IDs are required parameters for all
206
		 * Marketplace Web Service calls.
207
		 ***********************************************************************/
208
		//final String merchantId = "AF6E300VE0X4D";
209
		final String merchantId = "AF6E3O0VE0X4D";	
210
		// marketplaces to which this feed will be submitted; look at the
211
		// API reference document on the MWS website to see which marketplaces are
212
		// included if you do not specify the list yourself
213
		final IdList marketplaces = new IdList(Arrays.asList("A21TJRUUN4KGV"));
214
 
215
		SubmitFeedRequest requestpricing = new SubmitFeedRequest();
216
		requestpricing.setMerchant(merchantId);
217
		requestpricing.setMarketplaceIdList(marketplaces);
218
		requestpricing.setFeedType("_POST_PRODUCT_PRICING_DATA_");
219
		// MWS exclusively offers a streaming interface for uploading your
220
		// feeds. This is because
221
		// feed sizes can grow to the 1GB+ range - and as your business grows
222
		// you could otherwise
223
		// silently reach the feed size where your in-memory solution will no
224
		// longer work, leaving you
225
		// puzzled as to why a solution that worked for a long time suddenly
226
		// stopped working though
227
		// you made no changes. For the same reason, we strongly encourage you
228
		// to generate your feeds to
229
		// local disk then upload them directly from disk to MWS via Java -
230
		// without buffering them in JavaFileNotFoundException
231
		// memory in their entirety.
232
		// Note: MarketplaceWebServiceClient will not retry a submit feed request
233
		// because there is no way to reset the InputStream from our client. 
234
		// To enable retry, recreate the InputStream and resubmit the feed
235
		// with the new InputStream. 
236
		//
237
		try {
238
			createFBAPricingFeed();
239
			FileInputStream pricingfis = new FileInputStream(AMAZON_FBA_PRICING_XML);
240
			requestpricing.setContentMD5(computeContentMD5HeaderValue(pricingfis));
241
			requestpricing.setFeedContent(pricingfis);
242
		} catch (FileNotFoundException e) {
243
			// TODO Auto-generated catch block
244
			e.printStackTrace();
245
		}
246
 
247
		try {
248
			invokeSubmitFeed(service,requestpricing);
249
			Thread.sleep(180);
250
		} catch (InterruptedException e) {
251
			// TODO Auto-generated catch block
252
			e.printStackTrace();
253
		}
254
 
255
	}
256
 
257
	/**
258
	 * Submit Feed request sample Uploads a file for processing together with
259
	 * the necessary metadata to process the file, such as which type of feed it
260
	 * is. PurgeAndReplace if true means that your existing e.g. inventory is
261
	 * wiped out and replace with the contents ocf this feed - use with caution
262
	 * (the default is false).
263
	 * 
264
	 * @param service
265
	 *            instance of MarketplaceWebService service
266
	 * @param request
267
	 *            Action to invoke
268
	 * @throws InterruptedException 
269
	 */
270
	public static void invokeSubmitFeed(MarketplaceWebService service,
271
			SubmitFeedRequest request) throws InterruptedException {
272
		boolean retry = false;
273
		int retryCount = 0;
274
		while (!retry) {
275
			try {
276
 
277
				SubmitFeedResponse response = service.submitFeed(request);
278
 
279
				System.out.println("SubmitFeed Action Response");
280
				System.out
281
				.println("=============================================================================");
282
				System.out.println();
283
 
284
				System.out.print("    SubmitFeedResponse");
285
				System.out.println();
286
				FeedSubmissionInfo feedSubmissionInfo=null;
287
				if (response.isSetSubmitFeedResult()) {
288
					System.out.print("        SubmitFeedResult");
289
					System.out.println();
290
					SubmitFeedResult submitFeedResult = response
291
					.getSubmitFeedResult();
292
					if (submitFeedResult.isSetFeedSubmissionInfo()) {
293
						System.out.print("            FeedSubmissionInfo");
294
						System.out.println();
295
						feedSubmissionInfo = submitFeedResult
296
						.getFeedSubmissionInfo();
297
						if (feedSubmissionInfo.isSetFeedSubmissionId()) {
298
							System.out.print("                FeedSubmissionId");
299
							System.out.println();
300
							System.out.print("                    "
301
									+ feedSubmissionInfo.getFeedSubmissionId());
302
 
303
							System.out.println();
304
						}
305
						if (feedSubmissionInfo.isSetFeedType()) {
306
							System.out.print("                FeedType");
307
							System.out.println();
308
							System.out.print("                    "
309
									+ feedSubmissionInfo.getFeedType());
310
							System.out.println();
311
						}
312
						if (feedSubmissionInfo.isSetSubmittedDate()) {
313
							System.out.print("                SubmittedDate");
314
							System.out.println();
315
							System.out.print("                    "
316
									+ feedSubmissionInfo.getSubmittedDate());
317
							System.out.println();
318
						}
319
						if (feedSubmissionInfo.isSetFeedProcessingStatus()) {
320
							System.out
321
							.print("                FeedProcessingStatus");
322
							System.out.println();
323
							System.out.print("                    "
324
									+ feedSubmissionInfo.getFeedProcessingStatus());
325
							System.out.println();
326
						}
327
						if (feedSubmissionInfo.isSetStartedProcessingDate()) {
328
							System.out
329
							.print("                StartedProcessingDate");
330
							System.out.println();
331
							System.out
332
							.print("                    "
333
									+ feedSubmissionInfo
334
									.getStartedProcessingDate());
335
							System.out.println();
336
						}
337
						if (feedSubmissionInfo.isSetCompletedProcessingDate()) {
338
							System.out
339
							.print("                CompletedProcessingDate");
340
							System.out.println();
341
							System.out.print("                    "
342
									+ feedSubmissionInfo
343
									.getCompletedProcessingDate());
344
							System.out.println();
345
						}
346
					}
347
				}
348
				if (response.isSetResponseMetadata()) {
349
					System.out.print("        ResponseMetadata");
350
					System.out.println();
351
					ResponseMetadata responseMetadata = response
352
					.getResponseMetadata();
353
					if (responseMetadata.isSetRequestId()) {
354
						System.out.print("            RequestId");
355
						System.out.println();
356
						System.out.print("                "
357
								+ responseMetadata.getRequestId());
358
						System.out.println();
359
					}
360
				}
361
				System.out.println(response.getResponseHeaderMetadata());
362
				retry =true;
363
				System.out.println("============Sleeping For 10 Minutes=============");
364
				Thread.sleep(600000);
365
				CheckFeedSubmission checkResult = new CheckFeedSubmission();
366
				ProcessFeed feedProcessingResult=null;
367
				int checkResultCount=0;
368
				try {
369
					while (feedProcessingResult == null){
370
						feedProcessingResult = checkResult.getResult(feedSubmissionInfo.getFeedSubmissionId(),"FullFbaPricing",milliseconds,itemIdsToUpdate);
371
						if (feedProcessingResult == null){
372
							checkResultCount++;
373
							if (checkResultCount == 5){
374
								String text = "";
375
								String[] sendTo = { "eng@shop2020.in" };
376
								String emailSubjectTxt = "Unable To Receive FBA Pricing Feed Result.Submission Id "+feedSubmissionInfo.getFeedSubmissionId();
377
								String emailFromAddress = "build@shop2020.in";
378
								String password = "cafe@nes";
379
								GmailUtils mailer = new GmailUtils();
380
								try {
381
									mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
382
								}
383
								catch (Exception e) {
384
									e.printStackTrace();
385
								}
386
								System.exit(1);
387
							}
388
							System.out.println("=====Feed Result Not Ready Retry Again After 5 Minutes=============");
389
							Thread.sleep(300000);
390
 
391
						}
392
 
393
					}
394
 
395
				} catch (ParserConfigurationException e) {
396
					// TODO Auto-generated catch block
397
					e.printStackTrace();
398
				} catch (SAXException e) {
399
					// TODO Auto-generated catch block
400
					e.printStackTrace();
401
				} catch (IOException e) {
402
					// TODO Auto-generated catch block
403
					e.printStackTrace();
404
				}
405
				String emailSubjectTxt="";
406
				String[] sendTo;
407
				if (Boolean.valueOf(feedProcessingResult.getResult())){
408
					emailSubjectTxt = "FBA Pricing Feed Success "+sdf.format(cal.getTime());
409
					sendTo = new String[]{ "vikram.raghav@shop2020.in", "kshitij.sood@shop2020.in"};
410
				}
411
				else {
412
					emailSubjectTxt = "FBA Pricing Feed Failure "+sdf.format(cal.getTime());
413
					sendTo = new String[]{ "eng@shop2020.in"};
414
				}
415
				String text = "MessagesProcessed "+feedProcessingResult.getProcessed()+"\n"+"MessagesSuccessful "+feedProcessingResult.getSuccess()+"\n"+"" +
416
				"MessagesWithError "+feedProcessingResult.getError()+"\n"+"MessagesWithWarning "+feedProcessingResult.getWarn(); 
417
				String emailFromAddress = "build@shop2020.in";
418
				String password = "cafe@nes";
419
				GmailUtils mailer = new GmailUtils();
420
				try {
421
					mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, "/home/amazon/feedSubmission"+"FullFbaPricing"+"Result.xml");
422
				}
423
				catch (Exception ex) {
424
					ex.printStackTrace();
425
				}
426
				System.out.println();
427
			} catch (MarketplaceWebServiceException ex) {
428
 
429
				System.out.println("Caught Exception: " + ex.getMessage());
430
				System.out.println("Response Status Code: " + ex.getStatusCode());
431
				System.out.println("Error Code: " + ex.getErrorCode());
432
				System.out.println("Error Type: " + ex.getErrorType());
433
				System.out.println("Request ID: " + ex.getRequestId());
434
				System.out.print("XML: " + ex.getXML());
435
				System.out.println("ResponseHeaderMetadata: " + ex.getResponseHeaderMetadata());
436
 
437
				if (retryCount == 2) {
438
					StringWriter errors = new StringWriter();
439
					ex.printStackTrace(new PrintWriter(errors));
440
					String text = errors.toString(); 
441
					String[] sendTo = { "eng@shop2020.in" };
442
					String emailSubjectTxt = "Unable To Send FBA Pricing Feed ";
443
					String emailFromAddress = "build@shop2020.in";
444
					String password = "cafe@nes";
445
					GmailUtils mailer = new GmailUtils();
446
					try {
447
						mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
448
					}
449
					catch (Exception e) {
450
						e.printStackTrace();
451
					}
452
					System.exit(1);
453
				}
454
				retryCount++;
455
				Thread.sleep(60000);
456
			}
457
		}
458
	}
459
 
460
 
461
 
462
	public static void createFBAPricingFeed() throws CatalogServiceException, TException{
463
 
464
 
465
		File file = new File(AMAZON_FBA_PRICING_XML);
466
		AmazonEnvelope amazonenvelope =  new AmazonEnvelope();
467
		Header header = new Header();
468
		header.setDocumentVersion("1.0");
469
		header.setMerchantIdentifier("AF6E3O0VE0X4D");
470
		header.setOverrideReleaseId(null);
471
		amazonenvelope.setHeader(header);
472
		amazonenvelope.setMessageType("Price");
473
		amazonenvelope.setMarketplaceName(null);
474
		amazonenvelope.setPurgeAndReplace(PURGE_OR_REPLACE);
475
		JAXBContext context;
476
		Marshaller m=null;
477
		try {
478
			context = JAXBContext.newInstance(AmazonEnvelope.class);
479
			m = context.createMarshaller();
480
		} catch (JAXBException e1) {
481
			e1.printStackTrace();
482
		}
483
		XMLGregorianCalendar today = null;
484
		Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
485
 
486
		int currentMonth = localCalendar.get(Calendar.MONTH);
487
		int currentYear = localCalendar.get(Calendar.YEAR);
488
		int currentDayOfMonth = localCalendar.get(Calendar.DAY_OF_MONTH);
489
 
490
 
491
		try {
492
			today = DatatypeFactory.newInstance()
493
			.newXMLGregorianCalendar(
494
					new GregorianCalendar(currentYear,currentMonth,currentDayOfMonth));
495
			System.out.println(today);
496
		} catch (DatatypeConfigurationException e) {
497
			// TODO Auto-generated catch block
498
			e.printStackTrace(); 
499
		}
500
		amazonenvelope.setEffectiveDate(today);
501
		List <AmazonEnvelope.Message> messages = amazonenvelope.getMessage();
502
		int count=0;
503
		System.out.println("Inside price listing creation");
504
		itemIdsToUpdate = new ArrayList<Long>();
505
		for(Amazonlisted AItem:aItems){
506
			if(!AItem.isSuppressFbaPriceUpdate()){
507
				AmazonEnvelope.Message message = new AmazonEnvelope.Message();
508
				Price price = new Price();
509
				price.setSKU("FBA"+String.valueOf(AItem.getItemid()));
510
				OverrideCurrencyAmount overridecurrencyamount = new OverrideCurrencyAmount();
511
				overridecurrencyamount.setCurrency(BaseCurrencyCodeWithDefault.DEFAULT);
512
				overridecurrencyamount.setValue(BigDecimal.valueOf(AItem.getFbaPrice()));
513
				price.setStandardPrice(overridecurrencyamount);
514
				Random rand = new Random();
515
				message.setMessageID(BigInteger.valueOf(Math.abs(rand.nextInt())));
516
				message.setPrice(price);
517
				message.setOperationType("Update");
518
				messages.add(message);
519
				itemIdsToUpdate.add(AItem.getItemid());
520
				count++;
521
			}
522
		}
523
		try {
524
			m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
525
			m.marshal(amazonenvelope, file);
526
			m.marshal(amazonenvelope, System.out);
527
 
528
		} catch (Exception e) {
529
			// TODO Auto-generated catch block
530
			e.printStackTrace();
531
		}
532
 
533
 
534
	}
535
 
536
 
537
	public static String computeContentMD5HeaderValue( FileInputStream fis) {
538
		try {
539
			DigestInputStream dis = new DigestInputStream( fis,
540
					MessageDigest.getInstance( "MD5" ));
541
			byte[] buffer = new byte[8192];
542
			while( dis.read( buffer ) > 0 );
543
			String md5Content = new String(Base64.encodeBase64(dis.getMessageDigest().digest())
544
			);
545
			// Effectively resets the stream to be beginning of the file via a
546
			fis.getChannel().position( 0 );
547
			return md5Content;
548
		} catch (NoSuchAlgorithmException e) {
549
			// TODO Auto-generated catch block
550
			e.printStackTrace();
551
		} catch (IOException e) {
552
			// TODO Auto-generated catch block
553
			e.printStackTrace();
554
		}
555
		return null;
556
 
557
	}
558
 
559
 
560
 
561
 
562
 
563
}