Subversion Repositories SmartDukaan

Rev

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.math.BigDecimal;
27
import java.math.BigInteger;
28
import java.nio.channels.FileChannel;
29
import java.security.DigestInputStream;
30
import java.security.MessageDigest;
31
import java.security.NoSuchAlgorithmException;
32
import java.util.Arrays;
33
import java.util.Calendar;
34
import java.util.Date;
35
import java.util.GregorianCalendar;
36
import java.util.HashMap;
37
import java.util.Iterator;
38
import java.util.List;
39
import java.util.ArrayList;
40
import java.util.Map;
41
import java.util.Random;
42
import java.util.TimeZone;
43
 
44
import javax.xml.bind.JAXBContext;
45
import javax.xml.bind.JAXBException;
46
import javax.xml.bind.Marshaller;
47
import javax.xml.datatype.DatatypeConfigurationException;
48
import javax.xml.datatype.DatatypeConstants;
49
import javax.xml.datatype.DatatypeFactory;
50
import javax.xml.datatype.XMLGregorianCalendar;
51
 
52
import com.amazonaws.mws.*;
53
import com.amazonaws.mws.model.*;
54
import com.amazonaws.mws.mock.MarketplaceWebServiceMock;
55
import org.apache.commons.codec.binary.*;
56
 
57
import in.shop2020.feeds.products.AmazonEnvelope;
58
import in.shop2020.feeds.products.BaseCurrencyCodeWithDefault;
59
import in.shop2020.feeds.products.CE;
60
import in.shop2020.feeds.products.HandheldOrPDA;
61
import in.shop2020.feeds.products.Header;
62
import in.shop2020.feeds.products.Inventory;
63
import in.shop2020.feeds.products.Listings;
64
import in.shop2020.feeds.products.OverrideCurrencyAmount;
65
import in.shop2020.feeds.products.Price;
66
import in.shop2020.feeds.products.Product;
67
import in.shop2020.feeds.products.StandardProductID;
68
import in.shop2020.model.v1.catalog.CatalogService.Client;
69
import in.shop2020.model.v1.catalog.CatalogServiceException;
70
import in.shop2020.model.v1.catalog.Item;
71
import in.shop2020.model.v1.inventory.InventoryServiceException;
72
import in.shop2020.model.v1.inventory.ItemInventory;
73
import in.shop2020.thrift.clients.CatalogClient;
74
import in.shop2020.thrift.clients.InventoryClient;
75
import in.shop2020.thrift.clients.WarehouseClient;
76
import org.apache.thrift.TException;
77
import org.apache.thrift.transport.TTransportException;
78
 
79
/**
80
 * 
81
 * Submit Feed Samples
82
 * 
83
 * 
84
 */
85
public class SubmitFBAPricingFeed {
86
 
87
    /**
88
     * Just add a few required parameters, and try the service Submit Feed
89
     * functionality
90
     * 
91
     * @param args
92
     *            unused
93
     *            
94
     */
95
    /**
96
     * @param args
97
     * @throws TException 
98
     * @throws CatalogServiceException 
99
     */
100
 
101
	final public static String AMAZON_FBA_PRICING_XML   = "/home/vikram/Fbapricing.xml";
102
	final public static boolean PURGE_OR_REPLACE   = false;
103
	public static  List<Amazonlisted> aItems=null;
104
 
105
	static{
106
 
107
		CatalogClient catalogServiceClient = null;
108
		try {
109
			catalogServiceClient = new CatalogClient();
110
		} catch (TTransportException e) {
111
			// TODO Auto-generated catch block
112
			e.printStackTrace();
113
		}
114
		Client catalogClient = catalogServiceClient.getClient();
115
		try {
116
			aItems = catalogClient.getAllFbaListedItems();
117
 
118
		} catch (TException e) {
119
			// TODO Auto-generated catch block
120
			e.printStackTrace();
121
		}
122
 
123
	}
124
    public static void main(String... args) throws CatalogServiceException, TException {
125
 
126
        /**************************************************	**********************
127
         * Access Key ID and Secret Access Key ID, obtained from:
128
         * http://aws.amazon.com
129
         ***********************************************************************/
130
 
131
 
132
    	//public static final String marketplaceId = "A21TJRUUN4KGV";
133
 
134
 
135
 
136
 
137
        final String accessKeyId = "AKIAII3SGRXBJDPCHSGQ";
138
        final String secretAccessKey = "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";
139
 
140
        final String appName = "Test";
141
        final String appVersion = "1.0";
142
 
143
        MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();
144
 
145
        /************************************************************************
146
         * Uncomment to set the appropriate MWS endpoint.
147
         ************************************************************************/
148
        // US
149
        // config.setServiceURL("https://mws.amazonservices.com");
150
        // UK
151
        // config.setServiceURL("https://mws.amazonservices.co.uk");
152
        // Germany
153
        // config.setServiceURL("https://mws.amazonservices.de");
154
        // France
155
        // config.setServiceURL("https://mws.amazonservices.fr");
156
        // Italy
157
        // config.setServiceURL("https://mws.amazonservices.it");
158
        // Japan
159
        // config.setServiceURL("https://mws.amazonservices.jp");
160
        // China
161
        // config.setServiceURL("https://mws.amazonservices.com.cn");
162
        // Canada
163
        // config.setServiceURL("https://mws.amazonservices.ca");
164
        // India
165
        config.setServiceURL("https://mws.amazonservices.in");
166
 
167
        /************************************************************************
168
         * You can also try advanced configuration options. Available options are:
169
         *
170
         *  - Signature Version
171
         *  - Proxy Host and Proxy Port
172
         *  - User Agent String to be sent to Marketplace Web Service
173
         *
174
         ***********************************************************************/
175
 
176
        /************************************************************************
177
         * Instantiate Http Client Implementation of Marketplace Web Service        
178
         ***********************************************************************/
179
 
180
        MarketplaceWebService service = new MarketplaceWebServiceClient(
181
                accessKeyId, secretAccessKey, appName, appVersion, config);
182
 
183
 
184
        /************************************************************************
185
         * Setup request parameters and uncomment invoke to try out sample for
186
         * Submit Feed
187
         ***********************************************************************/
188
 
189
        /************************************************************************
190
         * Marketplace and Merchant IDs are required parameters for all
191
         * Marketplace Web Service calls.
192
         ***********************************************************************/
193
        //final String merchantId = "AF6E300VE0X4D";
194
        final String merchantId = "AF6E3O0VE0X4D";	
195
        // marketplaces to which this feed will be submitted; look at the
196
        // API reference document on the MWS website to see which marketplaces are
197
        // included if you do not specify the list yourself
198
        final IdList marketplaces = new IdList(Arrays.asList("A21TJRUUN4KGV"));
199
 
200
        SubmitFeedRequest requestpricing = new SubmitFeedRequest();
201
        requestpricing.setMerchant(merchantId);
202
        requestpricing.setMarketplaceIdList(marketplaces);
203
        requestpricing.setFeedType("_POST_PRODUCT_PRICING_DATA_");
204
        // MWS exclusively offers a streaming interface for uploading your
205
        // feeds. This is because
206
        // feed sizes can grow to the 1GB+ range - and as your business grows
207
        // you could otherwise
208
        // silently reach the feed size where your in-memory solution will no
209
        // longer work, leaving you
210
        // puzzled as to why a solution that worked for a long time suddenly
211
        // stopped working though
212
        // you made no changes. For the same reason, we strongly encourage you
213
        // to generate your feeds to
214
        // local disk then upload them directly from disk to MWS via Java -
215
        // without buffering them in JavaFileNotFoundException
216
        // memory in their entirety.
217
        // Note: MarketplaceWebServiceClient will not retry a submit feed request
218
        // because there is no way to reset the InputStream from our client. 
219
        // To enable retry, recreate the InputStream and resubmit the feed
220
        // with the new InputStream. 
221
        //
222
        try {
223
        	createFBAPricingFeed();
224
        	FileInputStream pricingfis = new FileInputStream(AMAZON_FBA_PRICING_XML);
225
        	requestpricing.setContentMD5(computeContentMD5HeaderValue(pricingfis));
226
			requestpricing.setFeedContent(pricingfis);
227
		} catch (FileNotFoundException e) {
228
			// TODO Auto-generated catch block
229
			e.printStackTrace();
230
		}
231
 
232
		try {
233
				invokeSubmitFeed(service,requestpricing);
234
				Thread.sleep(180);
235
			} catch (InterruptedException e) {
236
			// TODO Auto-generated catch block
237
			e.printStackTrace();
238
		}
239
 
240
    }
241
 
242
    /**
243
     * Submit Feed request sample Uploads a file for processing together with
244
     * the necessary metadata to process the file, such as which type of feed it
245
     * is. PurgeAndReplace if true means that your existing e.g. inventory is
246
     * wiped out and replace with the contents ocf this feed - use with caution
247
     * (the default is false).
248
     * 
249
     * @param service
250
     *            instance of MarketplaceWebService service
251
     * @param request
252
     *            Action to invoke
253
     */
254
    public static void invokeSubmitFeed(MarketplaceWebService service,
255
            SubmitFeedRequest request) {
256
        try {
257
 
258
            SubmitFeedResponse response = service.submitFeed(request);
259
 
260
            System.out.println("SubmitFeed Action Response");
261
            System.out
262
            .println("=============================================================================");
263
            System.out.println();
264
 
265
            System.out.print("    SubmitFeedResponse");
266
            System.out.println();
267
            if (response.isSetSubmitFeedResult()) {
268
                System.out.print("        SubmitFeedResult");
269
                System.out.println();
270
                SubmitFeedResult submitFeedResult = response
271
                .getSubmitFeedResult();
272
                if (submitFeedResult.isSetFeedSubmissionInfo()) {
273
                    System.out.print("            FeedSubmissionInfo");
274
                    System.out.println();
275
                    FeedSubmissionInfo feedSubmissionInfo = submitFeedResult
276
                    .getFeedSubmissionInfo();
277
                    if (feedSubmissionInfo.isSetFeedSubmissionId()) {
278
                        System.out.print("                FeedSubmissionId");
279
                        System.out.println();
280
                        System.out.print("                    "
281
                                + feedSubmissionInfo.getFeedSubmissionId());
282
 
283
                        System.out.println();
284
                    }
285
                    if (feedSubmissionInfo.isSetFeedType()) {
286
                        System.out.print("                FeedType");
287
                        System.out.println();
288
                        System.out.print("                    "
289
                                + feedSubmissionInfo.getFeedType());
290
                        System.out.println();
291
                    }
292
                    if (feedSubmissionInfo.isSetSubmittedDate()) {
293
                        System.out.print("                SubmittedDate");
294
                        System.out.println();
295
                        System.out.print("                    "
296
                                + feedSubmissionInfo.getSubmittedDate());
297
                        System.out.println();
298
                    }
299
                    if (feedSubmissionInfo.isSetFeedProcessingStatus()) {
300
                        System.out
301
                        .print("                FeedProcessingStatus");
302
                        System.out.println();
303
                        System.out.print("                    "
304
                                + feedSubmissionInfo.getFeedProcessingStatus());
305
                        System.out.println();
306
                    }
307
                    if (feedSubmissionInfo.isSetStartedProcessingDate()) {
308
                        System.out
309
                        .print("                StartedProcessingDate");
310
                        System.out.println();
311
                        System.out
312
                        .print("                    "
313
                                + feedSubmissionInfo
314
                                .getStartedProcessingDate());
315
                        System.out.println();
316
                    }
317
                    if (feedSubmissionInfo.isSetCompletedProcessingDate()) {
318
                        System.out
319
                        .print("                CompletedProcessingDate");
320
                        System.out.println();
321
                        System.out.print("                    "
322
                                + feedSubmissionInfo
323
                                .getCompletedProcessingDate());
324
                        System.out.println();
325
                    }
326
                }
327
            }
328
            if (response.isSetResponseMetadata()) {
329
                System.out.print("        ResponseMetadata");
330
                System.out.println();
331
                ResponseMetadata responseMetadata = response
332
                .getResponseMetadata();
333
                if (responseMetadata.isSetRequestId()) {
334
                    System.out.print("            RequestId");
335
                    System.out.println();
336
                    System.out.print("                "
337
                            + responseMetadata.getRequestId());
338
                    System.out.println();
339
                }
340
            }
341
            System.out.println(response.getResponseHeaderMetadata());
342
            System.out.println();
343
            System.out.println();
344
 
345
        } catch (MarketplaceWebServiceException ex) {
346
 
347
            System.out.println("Caught Exception: " + ex.getMessage());
348
            System.out.println("Response Status Code: " + ex.getStatusCode());
349
            System.out.println("Error Code: " + ex.getErrorCode());
350
            System.out.println("Error Type: " + ex.getErrorType());
351
            System.out.println("Request ID: " + ex.getRequestId());
352
            System.out.print("XML: " + ex.getXML());
353
            System.out.println("ResponseHeaderMetadata: " + ex.getResponseHeaderMetadata());
354
        }
355
    }
356
 
357
 
358
 
359
    public static void createFBAPricingFeed() throws CatalogServiceException, TException{
360
 
361
 
362
    	File file = new File(AMAZON_FBA_PRICING_XML);
363
    	AmazonEnvelope amazonenvelope =  new AmazonEnvelope();
364
    	Header header = new Header();
365
    	header.setDocumentVersion("1.0");
366
    	header.setMerchantIdentifier("AF6E3O0VE0X4D");
367
    	header.setOverrideReleaseId(null);
368
    	amazonenvelope.setHeader(header);
369
    	amazonenvelope.setMessageType("Price");
370
    	amazonenvelope.setMarketplaceName(null);
371
    	amazonenvelope.setPurgeAndReplace(PURGE_OR_REPLACE);
372
    	JAXBContext context;
373
    	Marshaller m=null;
374
    	try {
375
    		context = JAXBContext.newInstance(AmazonEnvelope.class);
376
    		m = context.createMarshaller();
377
    	} catch (JAXBException e1) {
378
    		e1.printStackTrace();
379
    	}
380
    	XMLGregorianCalendar today = null;
381
    	Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
382
 
383
    	int currentMonth = localCalendar.get(Calendar.MONTH);
384
    	int currentYear = localCalendar.get(Calendar.YEAR);
385
    	int currentDayOfMonth = localCalendar.get(Calendar.DAY_OF_MONTH);
386
 
387
 
388
    	try {
389
    		today = DatatypeFactory.newInstance()
390
    		.newXMLGregorianCalendar(
391
    				new GregorianCalendar(currentYear,currentMonth,currentDayOfMonth));
392
    	} catch (DatatypeConfigurationException e) {
393
    		// TODO Auto-generated catch block
394
    		e.printStackTrace(); 
395
    	}
396
    	amazonenvelope.setEffectiveDate(today);
397
    	List <AmazonEnvelope.Message> messages = amazonenvelope.getMessage();
398
    	int count=0;
399
    	System.out.println("Inside price listing creation");
400
    	for(Amazonlisted AItem:aItems){
401
    		AmazonEnvelope.Message message = new AmazonEnvelope.Message();
402
    		Price price = new Price();
403
    		price.setSKU("FBA"+String.valueOf(AItem.getItemid()));
404
    		OverrideCurrencyAmount overridecurrencyamount = new OverrideCurrencyAmount();
405
    		overridecurrencyamount.setCurrency(BaseCurrencyCodeWithDefault.DEFAULT);
406
    		overridecurrencyamount.setValue(BigDecimal.valueOf(AItem.getSellingPrice()));
407
    		price.setStandardPrice(overridecurrencyamount);
408
    		Random rand = new Random();
409
    		message.setMessageID(BigInteger.valueOf(Math.abs(rand.nextInt())));
410
    		message.setPrice(price);
411
    		message.setOperationType("Update");
412
    		messages.add(message);
413
    		count++;
414
    	}
415
 
416
    	try {
417
    		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
418
    		m.marshal(amazonenvelope, file);
419
    		m.marshal(amazonenvelope, System.out);
420
 
421
    	} catch (Exception e) {
422
    		// TODO Auto-generated catch block
423
    		e.printStackTrace();
424
    	}
425
 
426
 
427
    }
428
 
429
 
430
    public static String computeContentMD5HeaderValue( FileInputStream fis) {
431
    	try {
432
			DigestInputStream dis = new DigestInputStream( fis,
433
					MessageDigest.getInstance( "MD5" ));
434
			byte[] buffer = new byte[8192];
435
			while( dis.read( buffer ) > 0 );
436
			String md5Content = new String(Base64.encodeBase64(dis.getMessageDigest().digest())
437
				);
438
			// Effectively resets the stream to be beginning of the file via a
439
			fis.getChannel().position( 0 );
440
			return md5Content;
441
		} catch (NoSuchAlgorithmException e) {
442
			// TODO Auto-generated catch block
443
			e.printStackTrace();
444
		} catch (IOException e) {
445
			// TODO Auto-generated catch block
446
			e.printStackTrace();
447
		}
448
		return null;
449
 
450
 }
451
 
452
 
453
 
454
 
455
 
456
}