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