Subversion Repositories SmartDukaan

Rev

Rev 12832 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.support.utils;

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.thrift.clients.CatalogClient;
import in.shop2020.utils.GmailUtils;
import in.shop2020.serving.services.FlipkartPricingPannel;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UpdateFlipkartPricing extends Thread{
        private Float price;
        private String fksku;
        private Item item;
        private Long timestamp;
        //public String[] sendTo = new String[]{"vikram.raghav@shop2020.in"};
        private static Logger logger = LoggerFactory.getLogger(UpdateSDPricingUsingPanel.class);
        public String[] sendTo = new String[]{ "sandeep.sachdeva@shop2020.in", "vikram.raghav@shop2020.in", "rajneesh.arora@shop2020.in",
                        "khushal.bhatia@shop2020.in","manoj.kumar@saholic.com","chaitnaya.vats@saholic.com",
                        "yukti.jain@shop2020.in","chandan.kumar@shop2020.in","ankush.dhingra@shop2020.in","kshitij.sood@shop2020.in","anikendra.das@shop2020.in"};
        public String emailFromAddress = "build@shop2020.in";
        public String password = "cafe@nes";
        public UpdateFlipkartPricing(Float price,String fksku,Item item,Long timestamp){
                logger.info("Calling Update Snapdeal Price Constructor --" + " Price :" +price + " SKU at flipkart :"+fksku +" Item ID:" +item.getId());
                this.price = price;
                this.fksku = fksku;
                this.item = item;
                this.timestamp = timestamp; 
        }
        public UpdateFlipkartPricing() {
        }
        public static void main(String... args) throws ClientProtocolException, IOException, TTransportException, CatalogServiceException, TException{
                Item item = new CatalogClient().getClient().getItem(2231);
                UpdateFlipkartPricing updateFlipkartPricing = new UpdateFlipkartPricing(22200f,"1108903",item,System.currentTimeMillis());
                logger.info("Calling Thread to update price at snapdeal");
                updateFlipkartPricing.start();  

        }
        int updatePricing(Float price,String fksku,Item item,Long timestamp) throws JSONException{
                logger.info("Calling Update Flipkart Price Method --" + " Price :" +price + " Supc :"+fksku +" Item ID:" +item.getId());
                ClientConnectionManager connManager = new PoolingClientConnectionManager();
                DefaultHttpClient httpclient = new DefaultHttpClient(connManager);
                //httpclient = (DefaultHttpClient) WebClientWrapper.wrapClient(httpclient);
                //httpclient.getCredentialsProvider().setCredentials(
                //               new AuthScope("api.flipkart.net", 443),
                //               new UsernamePasswordCredentials("m2z93iskuj81qiid","0c7ab6a5-98c0-4cdc-8be3-72c591e0add4"));
                HttpPost httppost = new HttpPost("https://api.flipkart.net/sellers/skus/"+fksku+"/listings");
                String auth = "m2z93iskuj81qiid"+":"+"0c7ab6a5-98c0-4cdc-8be3-72c591e0add4";
                byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
                String authHeader = "Basic " + new String(encodedAuth);
                httppost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
                //StringBuffer jsonRequest = new StringBuffer();
                JSONObject outer = new JSONObject();
                JSONObject inner = new JSONObject();
                outer.put("skuId",fksku);
                inner.put("selling_price", String.valueOf(new Double(price).intValue()));
                outer.put("attributeValues", inner);
                /*jsonRequest.append("{\"skuId\":"+"\""+fksku+
                                 "\","+"\"attributeValues\""+":"+
                                 "{\"selling_price\""+":"+"\""+price+
                 "\"}");*/
                StringEntity input = null;
                try {
                        input = new StringEntity(outer.toString());
                        logger.info("Json input " + outer.toString());
                } catch (UnsupportedEncodingException e) {
                        logger.error("Unable to create request",e);
                }
                input.setContentType("application/json");
                httppost.setEntity(input);
                HttpResponse response = null;
                try {
                        logger.info("Trying to post");
                        response = httpclient.execute(httppost);
                } catch (IOException e) {
                        logger.error("Unable to post request",e);
                }
                BufferedReader rd = null;
                try {
                        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                } catch (IllegalStateException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                }
                String line;
                boolean updated = false;
                try {
                        while ((line = rd.readLine()) != null) {
                                logger.info("Response " + line);
                                if(line.equalsIgnoreCase("{\"status\":\"success\"}")){
                                        updated = true;
                                }
                        }
                } catch (IOException e2) {
                        e2.printStackTrace();
                }
                GmailUtils mailer = new GmailUtils();
                String text = "Product : " +getProductName(this.item) +"\n"+ 
                "Item ID : " +this.item.getId() +"\n"+
                "SKU at Flipkart : " +this.fksku +"\n"+
                "Updated Price : " +this.price;
                if(!updated){
                    FlipkartPricingPannel fkPricingPannel = new FlipkartPricingPannel();
                    try {
                        updated = fkPricingPannel.updatePrice(this.fksku, String.valueOf(this.price));
                logger.info("Value of updated" +updated);
            } catch (Exception e) {
                logger.info("Exception" + e);
            }
                }
                if(updated){
                        ArrayList<Long> updateList = new ArrayList<Long>();
                        try {
                                Client catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();

                                updateList.add(this.item.getId());
                                catalogClient.updateMarketPlacePriceUpdateStatus(updateList,this.timestamp,8);
                        } catch (TException e) {
                                try {
                                        new CatalogClient().getClient().updateMarketPlacePriceUpdateStatus(updateList, timestamp,8);
                                } catch (TTransportException e1) {
                                        e1.printStackTrace();
                                        logger.info("Exception" + e1);
                                } catch (TException e1) {
                                        e1.printStackTrace();
                                        logger.info("Exception" + e1);
                                }
                                logger.info("Exception" + e);
                        }
                        try{
                                mailer.sendSSLMessage(sendTo, "Price updated on Flipkart ( Item ID " + this.item.getId() + " )",text, emailFromAddress , password,new ArrayList<File>());
                        }
                        catch(Exception e){
                                logger.info("Exception"+e);
                        }
                }
                else{
                        try{
                                mailer.sendSSLMessage(sendTo, "Failed to update Price on Flipkart  ( Item ID " + this.item.getId() + " )",text, emailFromAddress , password,new ArrayList<File>());
                        }
                        catch(Exception e){
                                logger.info("Exception"+e);
                        }

                }
                return 1;
        }

        public void run()
        {
                try {
                        this.updatePricing(this.price,this.fksku,this.item,timestamp);
                } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        logger.error("Exception while updating prices",e);
                }

        }
        String getProductName(Item item){
                return getName(item.getBrand())+" " + getName(item.getModelName())+" " + getName(item.getModelNumber())+" " + getName(item.getColor()); 

        }
        String getName(String name){
                if(name==null || name.length()==0){
                        return "";
                }
                else{
                        return name;
                }
        }


}