Subversion Repositories SmartDukaan

Rev

Blame | Last modification | View Log | RSS feed

/*******************************************************************************
 *  Copyright 2009 Amazon Services.
 *  Licensed under the Apache License, Version 2.0 (the "License"); 
 *  
 *  You may not use this file except in compliance with the License. 
 *  You may obtain a copy of the License at: http://aws.amazon.com/apache2.0
 *  This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
 *  CONDITIONS OF ANY KIND, either express or implied. See the License for the 
 *  specific language governing permissions and limitations under the License.
 * ***************************************************************************** 
 *
 *  Marketplace Web Service Java Library
 *  API Version: 2009-01-01
 *  Generated: Wed Feb 18 13:28:48 PST 2009 
 * 
 */

package com.amazonaws.mws.samples;

import java.io.ByteArrayInputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.channels.FileChannel;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.ArrayList;
import java.util.TimeZone;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import com.amazonaws.mws.*;
import com.amazonaws.mws.model.*;
import com.amazonaws.mws.mock.MarketplaceWebServiceMock;
import org.apache.commons.codec.binary.*;

import in.shop2020.feeds.products.AmazonEnvelope;
import in.shop2020.feeds.products.BaseCurrencyCodeWithDefault;
import in.shop2020.feeds.products.CE;
import in.shop2020.feeds.products.HandheldOrPDA;
import in.shop2020.feeds.products.Header;
import in.shop2020.feeds.products.Inventory;
import in.shop2020.feeds.products.Listings;
import in.shop2020.feeds.products.OverrideCurrencyAmount;
import in.shop2020.feeds.products.Price;
import in.shop2020.feeds.products.Product;
import in.shop2020.feeds.products.StandardProductID;
import in.shop2020.model.v1.catalog.CatalogService.Client;
import in.shop2020.model.v1.catalog.CatalogServiceException;
import in.shop2020.model.v1.catalog.Item;
import in.shop2020.model.v1.inventory.InventoryServiceException;
import in.shop2020.model.v1.inventory.ItemInventory;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.InventoryClient;

import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;

/**
 * 
 * Submit Feed Samples
 * 
 * 
 */
public class SubmitFeed {

    /**
     * Just add a few required parameters, and try the service Submit Feed
     * functionality
     * 
     * @param args
     *            unused
     *            
     */
    /**
     * @param args
     * @throws TException 
     * @throws CatalogServiceException 
     */
        
        final public static String AMAZON_LISTING_XML = "/home/vikram/listing.xml";
        final public static String AMAZON_INVENTORY_XML = "/home/vikram/inventory.xml";
        final public static String AMAZON_PRICING_XML   = "/home/vikram/pricing.xml";
    public static void main(String... args) throws CatalogServiceException, TException {

        /************************************************************************
         * Access Key ID and Secret Access Key ID, obtained from:
         * http://aws.amazon.com
         ***********************************************************************/
        

        //public static final String marketplaceId = "A21TJRUUN4KGV";

        
                
        
        final String accessKeyId = "AKIAII3SGRXBJDPCHSGQ";
        final String secretAccessKey = "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";

        final String appName = "Test";
        final String appVersion = "1.0";

        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");
        // India
        config.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);


        /************************************************************************
         * Setup request parameters and uncomment invoke to try out sample for
         * Submit Feed
         ***********************************************************************/

        /************************************************************************
         * Marketplace and Merchant IDs are required parameters for all
         * Marketplace Web Service calls.
         ***********************************************************************/
        //final String merchantId = "AF6E300VE0X4D";
        final String merchantId = "AF6E3O0VE0X4D";      
        // marketplaces to which this feed will be submitted; look at the
        // API reference document on the MWS website to see which marketplaces are
        // included if you do not specify the list yourself
        final IdList marketplaces = new IdList(Arrays.asList(
                        "A21TJRUUN4KGV"));

        SubmitFeedRequest requestlisting = new SubmitFeedRequest();
        SubmitFeedRequest requestinventory = new SubmitFeedRequest();
        SubmitFeedRequest requestpricing = new SubmitFeedRequest();
        requestlisting.setMerchant(merchantId);
        requestinventory.setMerchant(merchantId);
        requestpricing.setMerchant(merchantId);
        requestlisting.setMarketplaceIdList(marketplaces);
        requestinventory.setMarketplaceIdList(marketplaces);
        requestpricing.setMarketplaceIdList(marketplaces);
        requestlisting.setFeedType("_POST_PRODUCT_DATA_");
        requestinventory.setFeedType("_POST_INVENTORY_AVAILABILITY_DATA_");
        requestpricing.setFeedType("_POST_PRODUCT_PRICING_DATA_");
        // MWS exclusively offers a streaming interface for uploading your
        // feeds. This is because
        // feed sizes can grow to the 1GB+ range - and as your business grows
        // you could otherwise
        // silently reach the feed size where your in-memory solution will no
        // longer work, leaving you
        // puzzled as to why a solution that worked for a long time suddenly
        // stopped working though
        // you made no changes. For the same reason, we strongly encourage you
        // to generate your feeds to
        // local disk then upload them directly from disk to MWS via Java -
        // without buffering them in JavaFileNotFoundException
        // memory in their entirety.
        // Note: MarketplaceWebServiceClient will not retry a submit feed request
        // because there is no way to reset the InputStream from our client. 
        // To enable retry, recreate the InputStream and resubmit the feed
        // with the new InputStream. 
        //
        try {
                
                createListingFeed();
                createInventoryFeed();
                createPricingFeed();
                FileInputStream listingfis = new FileInputStream(AMAZON_LISTING_XML);
                FileInputStream inventoryfis = new FileInputStream(AMAZON_INVENTORY_XML);
                FileInputStream pricingfis = new FileInputStream(AMAZON_PRICING_XML);
                requestlisting.setContentMD5(computeContentMD5HeaderValue(listingfis));
                requestinventory.setContentMD5(computeContentMD5HeaderValue(inventoryfis));
                requestpricing.setContentMD5(computeContentMD5HeaderValue(pricingfis));
                        requestlisting.setFeedContent(listingfis);
                        requestinventory.setFeedContent(inventoryfis);
                        requestpricing.setFeedContent(pricingfis);
                } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                
                try {
                        invokeSubmitFeed(service,requestlisting);
                        Thread.sleep(60000);
                        invokeSubmitFeed(service,requestinventory);
                        Thread.sleep(60000);
                        invokeSubmitFeed(service,requestpricing);
                        Thread.sleep(60000);
                } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }

    }

    /**
     * Submit Feed request sample Uploads a file for processing together with
     * the necessary metadata to process the file, such as which type of feed it
     * is. PurgeAndReplace if true means that your existing e.g. inventory is
     * wiped out and replace with the contents ocf this feed - use with caution
     * (the default is false).
     * 
     * @param service
     *            instance of MarketplaceWebService service
     * @param request
     *            Action to invoke
     */
    public static void invokeSubmitFeed(MarketplaceWebService service,
            SubmitFeedRequest request) {
        try {

            SubmitFeedResponse response = service.submitFeed(request);

            System.out.println("SubmitFeed Action Response");
            System.out
            .println("=============================================================================");
            System.out.println();

            System.out.print("    SubmitFeedResponse");
            System.out.println();
            if (response.isSetSubmitFeedResult()) {
                System.out.print("        SubmitFeedResult");
                System.out.println();
                SubmitFeedResult submitFeedResult = response
                .getSubmitFeedResult();
                if (submitFeedResult.isSetFeedSubmissionInfo()) {
                    System.out.print("            FeedSubmissionInfo");
                    System.out.println();
                    FeedSubmissionInfo feedSubmissionInfo = submitFeedResult
                    .getFeedSubmissionInfo();
                    if (feedSubmissionInfo.isSetFeedSubmissionId()) {
                        System.out.print("                FeedSubmissionId");
                        System.out.println();
                        System.out.print("                    "
                                + feedSubmissionInfo.getFeedSubmissionId());
                        System.out.println();
                    }
                    if (feedSubmissionInfo.isSetFeedType()) {
                        System.out.print("                FeedType");
                        System.out.println();
                        System.out.print("                    "
                                + feedSubmissionInfo.getFeedType());
                        System.out.println();
                    }
                    if (feedSubmissionInfo.isSetSubmittedDate()) {
                        System.out.print("                SubmittedDate");
                        System.out.println();
                        System.out.print("                    "
                                + feedSubmissionInfo.getSubmittedDate());
                        System.out.println();
                    }
                    if (feedSubmissionInfo.isSetFeedProcessingStatus()) {
                        System.out
                        .print("                FeedProcessingStatus");
                        System.out.println();
                        System.out.print("                    "
                                + feedSubmissionInfo.getFeedProcessingStatus());
                        System.out.println();
                    }
                    if (feedSubmissionInfo.isSetStartedProcessingDate()) {
                        System.out
                        .print("                StartedProcessingDate");
                        System.out.println();
                        System.out
                        .print("                    "
                                + feedSubmissionInfo
                                .getStartedProcessingDate());
                        System.out.println();
                    }
                    if (feedSubmissionInfo.isSetCompletedProcessingDate()) {
                        System.out
                        .print("                CompletedProcessingDate");
                        System.out.println();
                        System.out.print("                    "
                                + feedSubmissionInfo
                                .getCompletedProcessingDate());
                        System.out.println();
                    }
                }
            }
            if (response.isSetResponseMetadata()) {
                System.out.print("        ResponseMetadata");
                System.out.println();
                ResponseMetadata responseMetadata = response
                .getResponseMetadata();
                if (responseMetadata.isSetRequestId()) {
                    System.out.print("            RequestId");
                    System.out.println();
                    System.out.print("                "
                            + responseMetadata.getRequestId());
                    System.out.println();
                }
            }
            System.out.println(response.getResponseHeaderMetadata());
            System.out.println();
            System.out.println();

        } catch (MarketplaceWebServiceException ex) {

            System.out.println("Caught Exception: " + ex.getMessage());
            System.out.println("Response Status Code: " + ex.getStatusCode());
            System.out.println("Error Code: " + ex.getErrorCode());
            System.out.println("Error Type: " + ex.getErrorType());
            System.out.println("Request ID: " + ex.getRequestId());
            System.out.print("XML: " + ex.getXML());
            System.out.println("ResponseHeaderMetadata: " + ex.getResponseHeaderMetadata());
        }
    }
    
public static void createListingFeed() throws CatalogServiceException, TException{
                
                
                File file = new File(AMAZON_LISTING_XML);
                AmazonEnvelope amazonenvelope =  new AmazonEnvelope();
                Header header = new Header();
                header.setDocumentVersion("1.0");
                header.setMerchantIdentifier("AF6E3O0VE0X4D");
                header.setOverrideReleaseId(null);
                amazonenvelope.setHeader(header);
                amazonenvelope.setMessageType("Product");
                amazonenvelope.setMarketplaceName(null);
                amazonenvelope.setPurgeAndReplace(false);
                JAXBContext context;
                Marshaller m=null;
                try {
                        context = JAXBContext.newInstance(AmazonEnvelope.class);
                        m = context.createMarshaller();
                } catch (JAXBException e1) {
                        e1.printStackTrace();
                }
                
                
                XMLGregorianCalendar today = null;
                Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
            
            int currentMonth = localCalendar.get(Calendar.MONTH);
            int currentYear = localCalendar.get(Calendar.YEAR);
            int currentDayOfMonth = localCalendar.get(Calendar.DAY_OF_MONTH);


                try {
                  today = DatatypeFactory.newInstance()
                    .newXMLGregorianCalendar(
                                new GregorianCalendar(currentYear,currentMonth,currentDayOfMonth));
                } catch (DatatypeConfigurationException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                }

                amazonenvelope.setEffectiveDate(today);
                List <AmazonEnvelope.Message> messages = amazonenvelope.getMessage();
                AmazonEnvelope.Message message1 = new AmazonEnvelope.Message();
                //Listings listing1 = new Listings();
                Product product = new Product();
            CatalogClient catalogServiceClient = null;
                try {
                        catalogServiceClient = new CatalogClient();
                } catch (TTransportException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
            Client catalogClient = catalogServiceClient.getClient();
            in.shop2020.model.v1.catalog.Item thriftItem = catalogClient.getItem(2483);
            System.out.println(thriftItem);
            product.setSKU(String.valueOf(thriftItem.getId()));
            StandardProductID spid = new StandardProductID();
            spid.setType("EAN");
            spid.setValue("8806085002418");
            product.setItemPackageQuantity(BigInteger.valueOf(1));          
            product.setStandardProductID(spid);
            Product.DescriptionData descdata = new Product.DescriptionData();
            descdata.setBrand(thriftItem.getBrand());
            descdata.setAutographed(false);
                if(thriftItem.getModelName()!=null){
                        descdata.setTitle(thriftItem.getModelName());   
                }
                else{
                        descdata.setTitle(thriftItem.getModelNumber());
                }
            
            descdata.setManufacturer(thriftItem.getBrand());
            product.setDescriptionData(descdata);
            Product.ProductData productdata = new Product.ProductData();
            CE ce = new CE();
            ce.setColor(thriftItem.getColor());
            ce.setModel(thriftItem.getModelNumber());
            ce.setModelName(thriftItem.getModelName());
            HandheldOrPDA hhd = new HandheldOrPDA();
            CE.ProductType productype = new CE.ProductType();
            productype.setHandheldOrPDA(hhd);
            ce.setProductType(productype);
            productdata.setCE(ce);
            product.setProductData(productdata);
            message1.setMessageID(BigInteger.valueOf(41));
            //listing1.setProduct(product);
                //message1.setListings(listing1);
                message1.setProduct(product);
                messages.add(message1);
                try {
                        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                        m.marshal(amazonenvelope, file);
                        m.marshal(amazonenvelope, System.out);
                        
                } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                
                        
                }

public static void createInventoryFeed() throws CatalogServiceException, TException{
        
        
        File file = new File(AMAZON_INVENTORY_XML);
        AmazonEnvelope amazonenvelope =  new AmazonEnvelope();
        Header header = new Header();
        header.setDocumentVersion("1.0");
        header.setMerchantIdentifier("AF6E3O0VE0X4D");
        header.setOverrideReleaseId(null);
        amazonenvelope.setHeader(header);
        amazonenvelope.setMessageType("Inventory");
        amazonenvelope.setMarketplaceName(null);
        amazonenvelope.setPurgeAndReplace(false);
        JAXBContext context;
        Marshaller m=null;
        try {
                context = JAXBContext.newInstance(AmazonEnvelope.class);
                m = context.createMarshaller();
        } catch (JAXBException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
        }
        
        XMLGregorianCalendar today = null;
        Calendar localCalendar = Calendar.getInstance();
    
    int currentMonth = localCalendar.get(Calendar.MONTH);
    int currentYear = localCalendar.get(Calendar.YEAR);
    int currentDayOfMonth = localCalendar.get(Calendar.DAY_OF_MONTH);

        try {
          today = DatatypeFactory.newInstance()
            .newXMLGregorianCalendar(
                        new GregorianCalendar(currentYear,currentMonth,currentDayOfMonth));
        } catch (DatatypeConfigurationException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        amazonenvelope.setEffectiveDate(today);
        List <AmazonEnvelope.Message> messages = amazonenvelope.getMessage();
        AmazonEnvelope.Message message1 = new AmazonEnvelope.Message();
        //Listings listing1 = new Listings();
        Inventory inventory = new Inventory();
    InventoryClient inventoryServiceClient = null;
        try {
                inventoryServiceClient = new InventoryClient();
        } catch (TTransportException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
    ItemInventory availability=null;
        try {
                availability = inventoryClient.getItemInventoryByItemId(2483);
        } catch (InventoryServiceException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
        }
    if(availability.getAvailabilitySize() > 0)
    //inventory.setAvailable(true);
    inventory.setSKU("2483");
    inventory.setRestockDate(today);
    inventory.setFulfillmentLatency(BigInteger.valueOf(1));
    inventory.setQuantity(BigInteger.valueOf(availability.getAvailabilitySize()));
    //inventory.setQuantity(BigInteger.valueOf(availability.getAvailabilitySize()));
    inventory.setSwitchFulfillmentTo("MFN");
    message1.setMessageID(BigInteger.valueOf(42));
    //listing1.setProduct(product);
        //message1.setListings(listing1);
        message1.setInventory(inventory);
        messages.add(message1);
        try {
                m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                m.marshal(amazonenvelope, file);
                m.marshal(amazonenvelope, System.out);
                
        } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
        
                
        }

public static void createPricingFeed() throws CatalogServiceException, TException{
        
        
        File file = new File(AMAZON_PRICING_XML);
        AmazonEnvelope amazonenvelope =  new AmazonEnvelope();
        Header header = new Header();
        header.setDocumentVersion("1.0");
        header.setMerchantIdentifier("AF6E3O0VE0X4D");
        header.setOverrideReleaseId(null);
        amazonenvelope.setHeader(header);
        amazonenvelope.setMessageType("Price");
        amazonenvelope.setMarketplaceName(null);
        amazonenvelope.setPurgeAndReplace(false);
        JAXBContext context;
        Marshaller m=null;
        try {
                context = JAXBContext.newInstance(AmazonEnvelope.class);
                m = context.createMarshaller();
        } catch (JAXBException e1) {
                e1.printStackTrace();
        }
        XMLGregorianCalendar today = null;
        Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
    
    int currentMonth = localCalendar.get(Calendar.MONTH);
    int currentYear = localCalendar.get(Calendar.YEAR);
    int currentDayOfMonth = localCalendar.get(Calendar.DAY_OF_MONTH);


        try {
          today = DatatypeFactory.newInstance()
            .newXMLGregorianCalendar(
                        new GregorianCalendar(currentYear,currentMonth,currentDayOfMonth));
        } catch (DatatypeConfigurationException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        amazonenvelope.setEffectiveDate(today);
        List <AmazonEnvelope.Message> messages = amazonenvelope.getMessage();
        AmazonEnvelope.Message message1 = new AmazonEnvelope.Message();
        Price price = new Price();
        //Product product = new Product();
    CatalogClient catalogServiceClient = null;
        try {
                catalogServiceClient = new CatalogClient(); 
        } catch (TTransportException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
    Client catalogClient = catalogServiceClient.getClient();
    List<in.shop2020.model.v1.catalog.Amazonlisted> AItem = catalogClient.getAllAmazonListedItems();
    System.out.println("Amazon items are" + AItem);
    in.shop2020.model.v1.catalog.Item thriftItem = catalogClient.getItem(2483);
    price.setSKU(String.valueOf(thriftItem.getId()));
    OverrideCurrencyAmount overridecurrencyamount = new OverrideCurrencyAmount();
    overridecurrencyamount.setCurrency(BaseCurrencyCodeWithDefault.DEFAULT);
    overridecurrencyamount.setValue(BigDecimal.valueOf(thriftItem.getSellingPrice()));
    price.setStandardPrice(overridecurrencyamount);
    message1.setMessageID(BigInteger.valueOf(43));
    //listing1.setProduct(product);
        //message1.setListings(listing1);
        message1.setPrice(price);
        messages.add(message1);
        try {
                m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                m.marshal(amazonenvelope, file);
                m.marshal(amazonenvelope, System.out);
                
        } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
        
                
        }

    
    public static String computeContentMD5HeaderValue( FileInputStream fis) {
        try {
                        DigestInputStream dis = new DigestInputStream( fis,
                                        MessageDigest.getInstance( "MD5" ));
                        byte[] buffer = new byte[8192];
                        while( dis.read( buffer ) > 0 );
                        String md5Content = new String(Base64.encodeBase64(dis.getMessageDigest().digest())
                                );
 // Effectively resets the stream to be beginning of the file via a
                        fis.getChannel().position( 0 );
                        return md5Content;
                } catch (NoSuchAlgorithmException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                return null;
                
 }


    
    

}