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