Rev 15223 | Blame | Compare with Previous | Last modification | View Log | RSS feed
package in.shop2020;import in.shop2020.model.v1.catalog.MarketPlaceItemPrice;import in.shop2020.model.v1.catalog.SnapdealItemDetails;import in.shop2020.serving.services.SnapdealSessionCookie;import in.shop2020.thrift.clients.CatalogClient;import in.shop2020.utils.GmailUtils;import inventory.Inventory;import inventory.InventoryHistoryItems;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Map.Entry;import javax.mail.MessagingException;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.mime.MultipartEntity;import org.apache.http.entity.mime.content.ContentBody;import org.apache.http.entity.mime.content.FileBody;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.usermodel.Sheet;import org.apache.poi.ss.usermodel.Workbook;import org.apache.thrift.TException;import org.apache.thrift.transport.TTransportException;import org.json.JSONObject;import pricing.CurrentPricing;import pricing.CurrentPricingItems;import pricing.PricingHistory;import pricing.PricingHistoryItems;import com.google.gson.Gson;public class CreateSnapdealPricingFeed {private static DefaultHttpClient client = new DefaultHttpClient();private static long time = System.currentTimeMillis();private static String SNAPDEAL_PRICING_SHEET;static Map<String,SnapdealItemDetails> snapdealItemMap = new HashMap<String,SnapdealItemDetails>();static Map<Long,SnapdealItemDetails> itemSnapdealMap = new HashMap<Long,SnapdealItemDetails>();static List<MarketPlaceItemPrice> marketPlaceItemsPrices;static Map<String,CurrentPricing> currentPricesMap = new HashMap<String,CurrentPricing>();static PricingHistoryItems pricingHistoryItems;static CurrentPricingItems currentPricingItems;private static SimpleDateFormat sdf;private static String emailFromAddress;private static String password;private static GmailUtils mailer;private static String[] sendTo;private static Map<String, String> headers = new HashMap<String, String>();static {sdf = new java.text.SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");emailFromAddress = "build@shop2020.in";password = "cafe@nes";mailer = new GmailUtils();//sendTo = new String[]{"vikram.raghav@shop2020.in"};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","manisha.sharma@shop2020.in","chandan.kumar@shop2020.in","ankush.dhingra@shop2020.in"};CatalogClient catalogServiceClient = null;try {catalogServiceClient = new CatalogClient();} catch (TTransportException e1) {e1.printStackTrace();}in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = catalogServiceClient.getClient();List<SnapdealItemDetails> allSnapdealItems = null;try {allSnapdealItems = catalogClient.getAllSnapdealItems();time = System.currentTimeMillis();SNAPDEAL_PRICING_SHEET = "/home/snapdeal/snapdeal-pricing-"+time+".xls";marketPlaceItemsPrices = catalogClient.getMarketPlaceItemsForPriceUpdate(7);if(marketPlaceItemsPrices.size()==0){System.out.println("No Change in Price to update");try {mailer.sendSSLMessage(sendTo,"No changes in Snapdeal Item Prices "+ sdf.format(System.currentTimeMillis()),"No change in Snapdeal Prices to be update ", emailFromAddress, password, new ArrayList<File>());} catch (MessagingException e) {e.printStackTrace();}System.exit(0);}} catch (TException e) {e.printStackTrace();}for(SnapdealItemDetails snapdealItem:allSnapdealItems){snapdealItemMap.put(snapdealItem.getSkuAtSnapdeal(),snapdealItem);itemSnapdealMap.put(snapdealItem.getItem_id(), snapdealItem);}headers.put("User-agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11");headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");headers.put("Accept-Language", "en-US,en;q=0.8");headers.put("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");}public static void main(String... args) throws Exception{HttpGet get;BufferedReader rd= null;Gson gson = new Gson();int i = 1;boolean exitfetchingcurrent = true;System.out.println("Fetching current prices");HttpResponse response;SnapdealSessionCookie sdSessionCookie = new SnapdealSessionCookie();String cookies = "";JSONObject cookieObject = null;while(exitfetchingcurrent){get = new HttpGet("http://seller.snapdeal.com/pricing/search?gridType=normal&_search=false&nd="+time+"&rows=30&page="+i+"&sidx=&sord=asc");cookies = sdSessionCookie.getCookies();cookieObject = new JSONObject(cookies);for(String key:headers.keySet())get.addHeader(key, headers.get(key));get.addHeader("Cookie","SERVERID="+cookieObject.get("SERVERID")+";sfJSESSIONID="+cookieObject.get("sfJSESSIONID")+";");response = client.execute(get);rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));currentPricingItems = (CurrentPricingItems) gson.fromJson(rd, CurrentPricingItems.class);if(currentPricingItems.getRows().size()!=0){for(CurrentPricing currentPricing:currentPricingItems.getRows()){currentPricesMap.put(currentPricing.getSellerSku(),currentPricing);System.out.println(currentPricing.getSellerSku()+" "+currentPricing.getSellingPrice());}}else{exitfetchingcurrent = false;}i++;}FileInputStream fis = new FileInputStream("/root/code/trunk/SnapDealFeeds/SellerPricing.xls");Workbook hwb = new HSSFWorkbook(fis);Sheet sheet = hwb.getSheetAt(0);Row row;int iterator = 1;Map<String,Double> toUpdateSkuMap = new HashMap<String,Double>();for(MarketPlaceItemPrice marketPlaceItemPrice:marketPlaceItemsPrices){System.out.println(marketPlaceItemPrice.getItem_id() + " " + marketPlaceItemPrice.getSellingPrice());if(itemSnapdealMap.containsKey(marketPlaceItemPrice.getItem_id()) && marketPlaceItemPrice.getLastUpdatedOn() > marketPlaceItemPrice.getLastUpdatedOnMarketplace() && !marketPlaceItemPrice.isIsPriceOverride() && marketPlaceItemPrice.isIsListedOnSource()){if(currentPricesMap.containsKey(itemSnapdealMap.get(marketPlaceItemPrice.getItem_id()).getSkuAtSnapdeal()) && Double.parseDouble(currentPricesMap.get(itemSnapdealMap.get(marketPlaceItemPrice.getItem_id()).getSkuAtSnapdeal()).getSellingPrice()) != marketPlaceItemPrice.getSellingPrice() && marketPlaceItemPrice.getSellingPrice()!=0){row = sheet.getRow((short) iterator);row.getCell((short) 0).setCellValue(currentPricesMap.get(itemSnapdealMap.get(marketPlaceItemPrice.getItem_id()).getSkuAtSnapdeal()).getSupc());row.getCell((short) 1).setCellValue(itemSnapdealMap.get(marketPlaceItemPrice.getItem_id()).getSkuAtSnapdeal());row.getCell((short) 2).setCellValue(currentPricesMap.get(itemSnapdealMap.get(marketPlaceItemPrice.getItem_id()).getSkuAtSnapdeal()).getProductName());row.getCell((short) 3).setCellValue(marketPlaceItemPrice.getSellingPrice());row.getCell((short) 4).setCellValue(currentPricesMap.get(itemSnapdealMap.get(marketPlaceItemPrice.getItem_id()).getSkuAtSnapdeal()).getLive());toUpdateSkuMap.put(itemSnapdealMap.get(marketPlaceItemPrice.getItem_id()).getSkuAtSnapdeal(),marketPlaceItemPrice.getSellingPrice());iterator++;}}}if(iterator!=1){FileOutputStream fileOut = null;fis.close();try {System.out.println("Before writing file ");fileOut = new FileOutputStream(SNAPDEAL_PRICING_SHEET);} catch (FileNotFoundException e) {e.printStackTrace();}try {hwb.write(fileOut);} catch (IOException e) {e.printStackTrace();}HttpPost post = new HttpPost("http://seller.snapdeal.com/pricing/upload?uploadType=SP");cookies = sdSessionCookie.getCookies();cookieObject = new JSONObject(cookies);for(String key:headers.keySet())post.addHeader(key, headers.get(key));post.addHeader("Cookie","SERVERID="+cookieObject.get("SERVERID")+";sfJSESSIONID="+cookieObject.get("sfJSESSIONID")+";");File file = new File(SNAPDEAL_PRICING_SHEET);MultipartEntity mpEntity = new MultipartEntity();ContentBody cbFile = new FileBody(file,"application/vnd.ms-excel");mpEntity.addPart("file", cbFile);post.setEntity(mpEntity);response = client.execute(post);try {rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));} catch (IllegalStateException e1) {e1.printStackTrace();} catch (IOException e1) {e1.printStackTrace();}String line = "";String feedresponse = null;try {while ((line = rd.readLine()) != null) {feedresponse = line;}} catch (IOException e) {e.printStackTrace();}int retry = 5;boolean exitfetchinghistory;int successfullyUpdated;Map<String,Double> updatedSkuMap = new HashMap<String,Double>();System.out.println("Feed response " + feedresponse);if(feedresponse.contains("Error")){System.out.println("Error while uploading sheet");try {mailer.sendSSLMessage(sendTo,"Error at Snapdeal while Uploading Pricing feed "+ sdf.format(System.currentTimeMillis()),"This Error means that there is some problem while uploading pricing feed to snapdeal", emailFromAddress, password, new ArrayList<File>());} catch (MessagingException e) {e.printStackTrace();}System.exit(0);}String uploadId = "UID"+feedresponse.split("UID")[1];System.out.println("Feed Upload Id is " + uploadId);int j = 1;i=1;while(retry > 0){Thread.sleep(5*60*1000);exitfetchinghistory = true;System.out.println("Fetching history prices " + j);successfullyUpdated =0;while(exitfetchinghistory){get = new HttpGet("http://seller.snapdeal.com/pricing/search?gridType=history&_search=false&nd="+time+"&rows=30&page="+i+"&sidx=&sord=asc");cookies = sdSessionCookie.getCookies();cookieObject = new JSONObject(cookies);for(String key:headers.keySet())get.addHeader(key, headers.get(key));get.addHeader("Cookie","SERVERID="+cookieObject.get("SERVERID")+";sfJSESSIONID="+cookieObject.get("sfJSESSIONID")+";");response = client.execute(get);rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));pricingHistoryItems = (PricingHistoryItems) gson.fromJson(rd, PricingHistoryItems.class);if(pricingHistoryItems.getRows().size()!=0 && successfullyUpdated != (iterator - 1)){for(PricingHistory pricingHistory:pricingHistoryItems.getRows()){if(Long.parseLong(pricingHistory.getModifiedOn()) > time && pricingHistory.getApprovalStatus().equals("Done") && pricingHistory.getUploadId().equals(uploadId)){successfullyUpdated++;updatedSkuMap.put(pricingHistory.getSellerSku(),Double.parseDouble(pricingHistory.getLineitems().get(0).getNewValue()));System.out.println("SKU Updated " + pricingHistory.getSellerSku() + " " + pricingHistory.getUploadId());}}}else{exitfetchinghistory = false;if(successfullyUpdated == (iterator-1)){retry = 0;}}i++;}retry--;j++;}CatalogClient catalogServiceClient = null;try {catalogServiceClient = new CatalogClient();} catch (TTransportException e1) {e1.printStackTrace();}in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = catalogServiceClient.getClient();List<Long> updatedItems = new ArrayList<Long>();String tableHeader = "<tr>"+ "<td>" + "Product Name" +"</td>"+"<td>" + "Item ID" + "</td>"+"<td>" + "SKU at Snapdeal" + "</td>"+"<td>" + "Old Price" + "</td>"+"<td>" + "New Price" + "</td>"+"</tr>";if(toUpdateSkuMap.size() != updatedSkuMap.size()){StringBuffer notUpdatedMailBody =new StringBuffer();for(Entry<String, Double> entry:updatedSkuMap.entrySet()){toUpdateSkuMap.remove(entry.getKey());}for(Entry<String, Double> entry:toUpdateSkuMap.entrySet()){notUpdatedMailBody.append("<tr>" + "<td>" + currentPricesMap.get(entry.getKey()).getProductName() + "</td>"+"<td>" + snapdealItemMap.get(entry.getKey()).getItem_id() + "</td>"+"<td>" + snapdealItemMap.get(entry.getKey()).getSkuAtSnapdeal() + "</td>"+"<td>" + currentPricesMap.get(entry.getKey()).getSellingPrice() + "</td>"+"<td>" + entry.getValue() +"</td>");}String text = "<html><table border=\"1\" align=\"center\">"+ tableHeader+ notUpdatedMailBody.toString() + "</table></html>";System.out.println("SKUs not updated");try {mailer.sendSSLMessage(sendTo,"Snapdeal Item Prices were not updated "+ sdf.format(System.currentTimeMillis()),emailFromAddress, password, text);} catch (MessagingException e) {e.printStackTrace();}}if(updatedSkuMap.size()>0){StringBuffer updatedMailBody =new StringBuffer();for(Entry<String, Double> entry:updatedSkuMap.entrySet()){updatedMailBody.append("<tr>" + "<td>" + currentPricesMap.get(entry.getKey()).getProductName() + "</td>"+"<td>" + snapdealItemMap.get(entry.getKey()).getItem_id() + "</td>"+"<td>" + snapdealItemMap.get(entry.getKey()).getSkuAtSnapdeal() + "</td>"+"<td>" + currentPricesMap.get(entry.getKey()).getSellingPrice() + "</td>"+"<td>" + entry.getValue() +"</td>");updatedItems.add(snapdealItemMap.get(entry.getKey()).getItem_id());}try {catalogClient.updateMarketPlacePriceUpdateStatus(updatedItems,time,7);} catch (TException e) {try {new CatalogClient().getClient().updateMarketPlacePriceUpdateStatus(updatedItems, time,7);} catch (TTransportException e1) {e1.printStackTrace();} catch (TException e1) {e1.printStackTrace();}e.printStackTrace();}String text = "<html><table border=\"1\" align=\"center\">"+ tableHeader+ updatedMailBody.toString() + "</table></html>";try {System.out.println("Snapdeal Item Prices updated Successfully");if(updatedSkuMap.size()==1){mailer.sendSSLMessage(sendTo,updatedSkuMap.size()+" Snapdeal Item Price updated Successfully "+ sdf.format(System.currentTimeMillis()), emailFromAddress, password,text);}else{mailer.sendSSLMessage(sendTo,updatedSkuMap.size()+" Snapdeal Items Price updated Successfully "+ sdf.format(System.currentTimeMillis()), emailFromAddress, password,text);}} catch (MessagingException e) {e.printStackTrace();}}}else{try {System.out.println("Prices are same as the snapdeal prices");mailer.sendSSLMessage(sendTo,"No changes in Snapdeal Item Prices "+ sdf.format(System.currentTimeMillis()),"No change in Snapdeal Prices to be update ", emailFromAddress, password, new ArrayList<File>());} catch (MessagingException e) {e.printStackTrace();}}}}