Rev 8294 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
package com.amazonaws.mws.samples;import in.shop2020.model.v1.catalog.Amazonlisted;import in.shop2020.model.v1.inventory.AmazonFbaInventorySnapshot;import in.shop2020.model.v1.order.AmazonFbaSalesSnapshot;import in.shop2020.thrift.clients.CatalogClient;import in.shop2020.thrift.clients.InventoryClient;import in.shop2020.thrift.clients.TransactionClient;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.IOException;import java.io.OutputStream;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Arrays;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.TimeZone;import javax.xml.datatype.DatatypeConfigurationException;import javax.xml.datatype.DatatypeFactory;import javax.xml.datatype.Duration;import javax.xml.datatype.XMLGregorianCalendar;import org.apache.thrift.TException;import org.apache.thrift.transport.TTransportException;import au.com.bytecode.opencsv.CSVReader;import com.amazonaws.mws.MarketplaceWebService;import com.amazonaws.mws.MarketplaceWebServiceClient;import com.amazonaws.mws.MarketplaceWebServiceConfig;import com.amazonaws.mws.model.GetReportListRequest;import com.amazonaws.mws.model.GetReportRequest;import com.amazonaws.mws.model.IdList;import com.amazonaws.mws.model.RequestReportRequest;public class FetchAmazonSalesSnapshot {public static void main(String... args){/************************************************************************* Access Key ID and Secret Access Key ID, obtained from:* http://aws.amazon.com***********************************************************************/final String accessKeyId = "AKIAII3SGRXBJDPCHSGQ";final String secretAccessKey = "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";final String appName = "Test";final String appVersion = "1.0";final String merchantId = "AF6E3O0VE0X4D";MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();/************************************************************************* Uncomment to set the appropriate MWS endpoint.************************************************************************/// US// config.setServiceURL("https://mws.amazonservices.com");// UK// config.setServiceURL("https://mws.amazonservices.co.uk");// Germany// config.setServiceURL("https://mws.amazonservices.de");// France// config.setServiceURL("https://mws.amazonservices.fr");// Italy// config.setServiceURL("https://mws.amazonservices.it");// Japan// config.setServiceURL("https://mws.amazonservices.jp");// China// config.setServiceURL("https://mws.amazonservices.com.cn");// Canada// config.setServiceURL("https://mws.amazonservices.ca");// Indiaconfig.setServiceURL("https://mws.amazonservices.in");/************************************************************************* You can also try advanced configuration options. Available options are:** - Signature Version* - Proxy Host and Proxy Port* - User Agent String to be sent to Marketplace Web Service************************************************************************//************************************************************************* Instantiate Http Client Implementation of Marketplace Web Service***********************************************************************/MarketplaceWebService service = new MarketplaceWebServiceClient(accessKeyId, secretAccessKey, appName, appVersion, config);/************************************************************************* Uncomment to try out Mock Service that simulates Marketplace Web Service* responses without calling Marketplace Web Service service.** Responses are loaded from local XML files. You can tweak XML files to* experiment with various outputs during development** XML files available under com/amazonaws/mws/mock tree************************************************************************/// MarketplaceWebService service = new MarketplaceWebServiceMock();/************************************************************************* Setup request parameters and uncomment invoke to try out* sample for Request Report***********************************************************************//************************************************************************* Marketplace and Merchant IDs are required parameters for all* Marketplace Web Service calls.***********************************************************************/// marketplaces from which data should be included in the report; look at the// API reference document on the MWS website to see which marketplaces are// included if you do not specify the list yourselffinal IdList marketplaces = new IdList(Arrays.asList("A21TJRUUN4KGV"));RequestReportRequest orderreportrequest = new RequestReportRequest().withMerchant(merchantId).withMarketplaceIdList(marketplaces).withReportType("_GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_").withReportOptions("ShowSalesChannel=true");RequestReportRequest inventoryhealthreportrequest = new RequestReportRequest().withMerchant(merchantId).withMarketplaceIdList(marketplaces).withReportType("_GET_FBA_FULFILLMENT_INVENTORY_HEALTH_DATA_").withReportOptions("ShowSalesChannel=true");DatatypeFactory df = null;try {df = DatatypeFactory.newInstance();} catch (DatatypeConfigurationException e) {e.printStackTrace();throw new RuntimeException(e);}long ordertimediff = System.currentTimeMillis() - 7*24*60*60*1000;GregorianCalendar ost = new GregorianCalendar();ost.setTimeInMillis(ordertimediff);XMLGregorianCalendar orderStartDate = df.newXMLGregorianCalendar(ost);XMLGregorianCalendar orderEndDate = df.newXMLGregorianCalendar(new GregorianCalendar());System.out.println("Order Start Date " + orderStartDate + "Order End Date " + orderEndDate);orderreportrequest.setStartDate(orderStartDate);orderreportrequest.setEndDate(orderEndDate);long inventorytimediff = System.currentTimeMillis() - 7*24*60*60*1000;GregorianCalendar ist = new GregorianCalendar();ist.setTimeInMillis(inventorytimediff);ist.setTimeInMillis(ordertimediff);XMLGregorianCalendar inventoryStartDate = df.newXMLGregorianCalendar(ist);XMLGregorianCalendar inventoryEndDate = df.newXMLGregorianCalendar(new GregorianCalendar());System.out.println("Inventory Start Date " + inventoryStartDate + "Inventory End Date " + inventoryEndDate);inventoryhealthreportrequest.setStartDate(inventoryStartDate);inventoryhealthreportrequest.setEndDate(inventoryEndDate);Map<String,String> requestIdreportIdmap;String orderreportrequestId = RequestReportSample.invokeRequestReport(service, orderreportrequest);String inventoryhealthreportrequestId = RequestReportSample.invokeRequestReport(service, inventoryhealthreportrequest);while(true){GetReportListRequest requestreportlist = new GetReportListRequest();requestreportlist.setMerchant( merchantId );final IdList requestIdList = new IdList(Arrays.asList(orderreportrequestId,inventoryhealthreportrequestId));requestreportlist.setReportRequestIdList(requestIdList);requestIdreportIdmap = GetReportListSample.invokeGetReportList(service, requestreportlist);if(requestIdreportIdmap.get(orderreportrequestId)!=null && requestIdreportIdmap.get(inventoryhealthreportrequestId)!=null){GetReportRequest requestorderreport = new GetReportRequest();GetReportRequest requestinventoryhealthreport = new GetReportRequest();requestorderreport.setMerchant( merchantId );requestinventoryhealthreport.setMerchant(merchantId);requestorderreport.setReportId( requestIdreportIdmap.get(orderreportrequestId));requestinventoryhealthreport.setReportId(requestIdreportIdmap.get(inventoryhealthreportrequestId));OutputStream orderreport=null;OutputStream inventoryhealthreport=null;try {orderreport = new FileOutputStream( "/home/vikram/Desktop/amazonorderreport.csv" );inventoryhealthreport = new FileOutputStream( "/home/vikram/Desktop/inventoryhealthreport.csv" );} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}requestorderreport.setReportOutputStream(orderreport);requestinventoryhealthreport.setReportOutputStream(inventoryhealthreport);GetReportSample.invokeGetReport(service, requestorderreport);GetReportSample.invokeGetReport(service, requestinventoryhealthreport);System.out.println("Order and Inventory Reports are ready please check");CSVReader orderreportreader = null;CSVReader inventoryhealthreportreader = null;try {orderreportreader = new CSVReader(new FileReader("/home/vikram/Desktop/amazonorderreport.csv"),'\t');inventoryhealthreportreader = new CSVReader(new FileReader("/home/vikram/Desktop/inventoryhealthreport.csv"),'\t');} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}String [] nextLine;try {int count =1;Map<Date,Map<Long,Integer>> orderDateItemIdCountMap = new HashMap<Date,Map<Long,Integer>>();while ((nextLine = orderreportreader.readNext()) != null) {if(count!=1 && nextLine[5].equalsIgnoreCase("Amazon") && (nextLine[13].equalsIgnoreCase("Unshipped") || nextLine[13].equalsIgnoreCase("Shipped"))){SimpleDateFormat istFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");istFormatter .setLenient(false);TimeZone zone= TimeZone.getTimeZone("GMT");istFormatter.setTimeZone(zone);Date date = istFormatter.parse(nextLine[2]);SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");Date date_key = dateFormat.parse(dateFormat.format(date));System.out.println(nextLine[0]+" "+date_key+" "+ nextLine[11] +" " + nextLine[13] + " " + nextLine[14]);Long itemid = Long.parseLong(nextLine[11].replaceAll("FBA",""));Integer qty = new Integer(nextLine[14]);if(orderDateItemIdCountMap.containsKey(date_key)){if(orderDateItemIdCountMap.get(date_key).containsKey(itemid)){orderDateItemIdCountMap.get(date_key).put(itemid,orderDateItemIdCountMap.get(date_key).get(itemid)+qty);}else{orderDateItemIdCountMap.get(date_key).put(itemid,qty);}}else{Map<Long,Integer> itemIdcountMap = new HashMap<Long,Integer>();itemIdcountMap.put(itemid,qty);orderDateItemIdCountMap.put(date_key,itemIdcountMap);}}count++;}InventoryClient inventoryServiceClient = null;TransactionClient transactionServiceClient = null;CatalogClient catalogServiceClient = null;try {inventoryServiceClient = new InventoryClient();transactionServiceClient = new TransactionClient();catalogServiceClient = new CatalogClient();//catalogServiceClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();in.shop2020.model.v1.order.TransactionService.Client transactionClient = transactionServiceClient.getClient();in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = catalogServiceClient.getClient();SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");Date date_today = dateFormat.parse(dateFormat.format(new Date()));for(AmazonFbaInventorySnapshot amazonFbaInventory:inventoryClient.getAllNonzeroAmazonFbaItemInventory()){if(orderDateItemIdCountMap.containsKey(date_today) ){if(!orderDateItemIdCountMap.get(date_today).containsKey(amazonFbaInventory.getItem_id())){orderDateItemIdCountMap.get(date_today).put(amazonFbaInventory.getItem_id(),0);}}else{Map<Long,Integer> itemIdcountMap = new HashMap<Long,Integer>();itemIdcountMap.put(amazonFbaInventory.getItem_id(),0);orderDateItemIdCountMap.put(date_today,itemIdcountMap);}}orderDateItemIdCountMap.get(date_today);Map<Long,Double> itemIdSalePriceMap = new HashMap<Long,Double>();Map<Long,Double> itemIdminFBAPriceMap = new HashMap<Long,Double>();Map<Long,Double> itemIdminMFNPriceMap = new HashMap<Long,Double>();count=1;while ((nextLine = inventoryhealthreportreader.readNext()) != null ) {if(count!=1){//System.out.println(nextLine[1] +" "+ nextLine[31] +" " + nextLine[32] + " " + nextLine[34]);Long item_id = Long.parseLong(nextLine[1].replaceAll("FBA",""));Double salePrice = Double.parseDouble(nextLine[31]);Double minFBAPrice = Double.parseDouble(nextLine[32]);Double minMFNPrice = Double.parseDouble(nextLine[34]);itemIdSalePriceMap.put(item_id,salePrice);itemIdminFBAPriceMap.put(item_id,minFBAPrice);itemIdminMFNPriceMap.put(item_id,minMFNPrice);}count++;}boolean oos;for (Map.Entry<Date, Map<Long, Integer>> entry : orderDateItemIdCountMap.entrySet()){Date orderDate = entry.getKey();for(Map.Entry<Long, Integer> entry1 :entry.getValue().entrySet()){Long inventory = inventoryClient.getAmazonFbaItemInventory(entry1.getKey());oos=false;if(inventory==0 && entry1.getValue()==0)oos=true;Long item_id = entry1.getKey();System.out.println(orderDate +","+entry1.getKey()+","+entry1.getValue()+","+ inventory +","+ oos+","+itemIdSalePriceMap.get(item_id)+","+itemIdminFBAPriceMap.get(item_id)+","+itemIdminMFNPriceMap.get(item_id));AmazonFbaSalesSnapshot amazonfbasalessnapshot = new AmazonFbaSalesSnapshot();amazonfbasalessnapshot.setDateOfSale(orderDate.getTime());amazonfbasalessnapshot.setItem_id(entry1.getKey());amazonfbasalessnapshot.setOrderCount(entry1.getValue());amazonfbasalessnapshot.setIsOutOfStock(oos);Amazonlisted amazon_item = catalogClient.getAmazonItemDetails(item_id);if(itemIdSalePriceMap.containsKey(item_id) && itemIdSalePriceMap.get(item_id)!=0){amazonfbasalessnapshot.setSalePrice(itemIdSalePriceMap.get(item_id));}else{amazonfbasalessnapshot.setSalePrice(amazon_item.getFbaPrice());}if(itemIdminMFNPriceMap.containsKey(item_id) && itemIdminMFNPriceMap.get(item_id)!=0){amazonfbasalessnapshot.setMinFbaPrice(itemIdminMFNPriceMap.get(item_id));}if(itemIdminMFNPriceMap.containsKey(item_id) && itemIdminMFNPriceMap.get(item_id)!=0){amazonfbasalessnapshot.setMinMfnPrice(itemIdminMFNPriceMap.get(item_id));}amazonfbasalessnapshot.setAmazonFbaInventory(inventory);transactionClient.addOrUpdateAmazonFbaSalesSnapshot(amazonfbasalessnapshot);}}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (TException e) {// TODO Auto-generated catch blocke.printStackTrace();}break;}else{System.out.println("Report not ready");try {Thread.sleep(5*60*1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}// Note that depending on the type of report being downloaded, a report can reach// sizes greater than 1GB. For this reason we recommend that you _always_ program to// MWS in a streaming fashion. Otherwise, as your business grows you may silently reach// the in-memory size limit and have to re-work your solution.//}}