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