Subversion Repositories SmartDukaan

Rev

Rev 8143 | Rev 9847 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1678 rajveer 1
package in.shop2020.util;
2
 
5113 amit.gupta 3
import in.shop2020.logistics.DeliveryType;
4
import in.shop2020.logistics.LogisticsInfo;
5
import in.shop2020.logistics.LogisticsService;
4188 varun.gupt 6
import in.shop2020.metamodel.core.Entity;
4802 amit.gupta 7
import in.shop2020.metamodel.definitions.Catalog;
6025 amit.gupta 8
import in.shop2020.metamodel.definitions.Category;
4802 amit.gupta 9
import in.shop2020.metamodel.definitions.DefinitionsContainer;
4188 varun.gupt 10
import in.shop2020.metamodel.util.CreationUtils;
5945 mandeep.dh 11
import in.shop2020.model.v1.catalog.CatalogService.Client;
1678 rajveer 12
import in.shop2020.model.v1.catalog.Item;
6025 amit.gupta 13
import in.shop2020.model.v1.catalog.ItemShippingInfo;
4188 varun.gupt 14
import in.shop2020.model.v1.catalog.status;
15
import in.shop2020.model.v1.user.ItemCouponDiscount;
16
import in.shop2020.thrift.clients.CatalogClient;
5113 amit.gupta 17
import in.shop2020.thrift.clients.LogisticsClient;
4188 varun.gupt 18
import in.shop2020.thrift.clients.PromotionClient;
6027 amit.gupta 19
import in.shop2020.utils.ConfigClientKeys;
8143 amit.gupta 20
import in.shop2020.utils.GmailUtils;
4188 varun.gupt 21
 
2130 rajveer 22
import java.io.File;
5612 amit.gupta 23
import java.io.FileInputStream;
7837 amit.gupta 24
import java.io.FileNotFoundException;
25
import java.io.FileReader;
5612 amit.gupta 26
import java.io.IOException;
7837 amit.gupta 27
import java.io.Reader;
5612 amit.gupta 28
import java.nio.MappedByteBuffer;
29
import java.nio.channels.FileChannel;
30
import java.nio.charset.Charset;
1678 rajveer 31
import java.util.ArrayList;
5612 amit.gupta 32
import java.util.Arrays;
8143 amit.gupta 33
import java.util.Calendar;
4143 varun.gupt 34
import java.util.HashMap;
1678 rajveer 35
import java.util.List;
36
import java.util.Map;
37
 
8143 amit.gupta 38
import javax.mail.MessagingException;
7506 amit.gupta 39
import javax.xml.transform.Result;
40
import javax.xml.transform.Source;
41
import javax.xml.transform.Transformer;
42
import javax.xml.transform.TransformerConfigurationException;
43
import javax.xml.transform.TransformerException;
44
import javax.xml.transform.TransformerFactory;
45
import javax.xml.transform.dom.DOMSource;
46
import javax.xml.transform.stream.StreamResult;
47
 
4202 varun.gupt 48
import org.apache.commons.lang.StringEscapeUtils;
1678 rajveer 49
import org.apache.commons.lang.StringUtils;
7506 amit.gupta 50
import org.apache.commons.logging.Log;
51
import org.apache.commons.logging.LogFactory;
52
import org.apache.xerces.parsers.DOMParser;
4143 varun.gupt 53
import org.json.JSONObject;
7506 amit.gupta 54
import org.w3c.dom.Document;
55
import org.w3c.dom.Node;
56
import org.w3c.dom.NodeList;
1678 rajveer 57
 
7837 amit.gupta 58
import com.google.gson.Gson;
59
import com.google.gson.reflect.TypeToken;
60
 
1678 rajveer 61
/**
62
 * Command line utility to generate xml file for partners
63
 * 
64
 * @author rajveer
65
 *
66
 */
67
public class ProductListGenerator {
7506 amit.gupta 68
 
69
	private static Log log = LogFactory.getLog(ContentGenerationUtility.class);
1678 rajveer 70
 
71
	private String[] xmlIndentation = {"", "    ", "        ", "            ","                "};
5612 amit.gupta 72
	private Client cc = null;
6602 amit.gupta 73
	List <Long> inStockCatalogItemIds = new ArrayList<Long>();
74
 
2367 rajveer 75
	public Map<Long, List<Item>> entityIdItemMap;
5113 amit.gupta 76
	private static final String DEFAULT_PINCODE = "110001";
4802 amit.gupta 77
	DefinitionsContainer defContainer = Catalog.getInstance().getDefinitionsContainer();
6025 amit.gupta 78
	private List<Long> validParentCategories = Arrays.asList((long)Utils.LAPTOPS_CATEGORY, (long)Utils.CAMERAS_CATEGORY, (long)Utils.MOBILE_PHONES_CATAGORY, (long)Utils.TABLETS_CATEGORY);
7629 amit.gupta 79
	/*private List<Long> voucherEntities = new ArrayList<Long>();*/
1678 rajveer 80
 
2367 rajveer 81
	public ProductListGenerator(Map<Long, List<Item>> entityIdItemMap) throws Exception {
82
		this.entityIdItemMap = entityIdItemMap;
1678 rajveer 83
	}
84
 
7629 amit.gupta 85
	public ProductListGenerator(List<Item> items) throws Exception {
86
		populateEntityIdItemMap(items);
87
	}
1678 rajveer 88
 
7629 amit.gupta 89
 
1678 rajveer 90
	/**
2367 rajveer 91
	 * Get the url of the entity
1678 rajveer 92
	 * @param expEntity
93
	 * @return url
94
	 */
2367 rajveer 95
	private String getProductURL(long entityId, Item item){
4802 amit.gupta 96
		//long rootCategoryId = catm.getCategory(item.getCategory()).getParent_category_id();
97
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
98
 
99
		String url = "http://www.saholic.com/" + parentCategory.getLabel().toLowerCase().replace(' ', '-') + "/";
2367 rajveer 100
		String productUrl = ((item.getBrand() != null) ? item.getBrand().trim() + " " : "").toLowerCase().replace(' ', '-')
101
        + "-" + ((item.getModelName() != null) ? item.getModelName().trim() + " " : "").toLowerCase().replace(' ', '-') 
102
	    + "-" + (( item.getModelNumber() != null ) ? item.getModelNumber().trim() + " ": "" ).toLowerCase().replace(' ', '-')
103
        + "-" + entityId;
1678 rajveer 104
		productUrl = productUrl.replaceAll("/", "-");
105
		url = url + productUrl;
2367 rajveer 106
		url = url.replaceAll("-+", "-");
1678 rajveer 107
		return url;
108
	}
6040 amit.gupta 109
 
110
 
111
	/**
112
	 * Get the url of the entity
113
	 * @param expEntity
114
	 * @return url
115
	 */
116
	private String getProductURL(long entityId, Item item, int affiliateId){
117
		//long rootCategoryId = catm.getCategory(item.getCategory()).getParent_category_id();
118
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
119
 
120
		String url = "http://www.saholic.com/" + parentCategory.getLabel().toLowerCase().replace(' ', '-') + "/";
121
		String productUrl = ((item.getBrand() != null) ? item.getBrand().trim() + " " : "").toLowerCase().replace(' ', '-')
122
		+ "-" + ((item.getModelName() != null) ? item.getModelName().trim() + " " : "").toLowerCase().replace(' ', '-') 
123
		+ "-" + (( item.getModelNumber() != null ) ? item.getModelNumber().trim() + " ": "" ).toLowerCase().replace(' ', '-')
124
		+ "-" + entityId;
125
		productUrl = productUrl.replaceAll("/", "-");
126
		url = url + productUrl;
127
		url = url.replaceAll("-+", "-");
128
		return url + "?afid=" + affiliateId;
129
	}
1678 rajveer 130
 
2367 rajveer 131
 
132
 
1678 rajveer 133
	/**
3964 rajveer 134
	 * Get the minimum mrp of the items
135
	 * @param items
136
	 * @return
137
	 */
138
	private double getMinMRP(List<Item> items){
139
        double minPrice = Double.MAX_VALUE;
140
        for(Item item: items){
141
            if(minPrice > item.getMrp()){
142
                minPrice =  item.getMrp();
143
            }
144
        }
145
        return minPrice;
146
    }
147
 
6602 amit.gupta 148
	public List<Long> getInStockCatalogItemIds() {
149
		return inStockCatalogItemIds;
150
	}
3964 rajveer 151
 
6602 amit.gupta 152
 
153
 
3964 rajveer 154
 
155
	/**
2367 rajveer 156
	 * Get the minimum price of the items
157
	 * @param items
158
	 * @return
159
	 */
160
	private double getMinPrice(List<Item> items){
161
        double minPrice = Double.MAX_VALUE;
162
        for(Item item: items){
163
            if(minPrice > item.getSellingPrice()){
164
                minPrice = item.getSellingPrice();
165
            }
166
        }
167
        return minPrice;
168
    }
169
 
170
	/**
171
	 * Check whether product is mobile or not
172
	 * @param item
173
	 * @return
174
	 */
175
	private boolean isMobile(Item item){
4802 amit.gupta 176
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
177
		return parentCategory.getID() == Utils.MOBILE_PHONES_CATAGORY;
2367 rajveer 178
	}
179
 
180
	/**
5229 varun.gupt 181
	 * Checks whether a product is tablet or not
182
	 */
183
	private boolean isTablet(Item item) {
184
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
185
		return parentCategory.getID() == Utils.TABLETS_CATEGORY;
186
	}
5935 amit.gupta 187
 
188
	/**
189
	 * Checks whether a product is camera or not
190
	 */
191
	private boolean isCamera(Item item) {
192
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
193
		return parentCategory.getID() == Utils.CAMERAS_CATEGORY;
194
	}
5229 varun.gupt 195
 
196
	/**
4143 varun.gupt 197
	 * Checks whether a product is laptop or not
198
	 */
199
	private boolean isLaptop(Item item) {
4802 amit.gupta 200
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
201
		return parentCategory.getID() == Utils.LAPTOPS_CATEGORY;
4143 varun.gupt 202
	}
203
 
204
	/**
5355 varun.gupt 205
	 * Checks whether a product is accessory or not
206
	 */
207
	private boolean isAccessory(Item item)	{
208
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
209
		return parentCategory.getID() == Utils.MOBILE_ACCESSORIES_CATEGORY || parentCategory.getID() == Utils.LAPTOP_ACCESSORIES_CATEGORY;
210
	}
211
 
212
	/**
2367 rajveer 213
	 * 
214
	 * @param item
215
	 * @return
216
	 */
217
	private String getProductTitle(Item item){
2542 rajveer 218
		String title = ((item.getBrand() != null) ? item.getBrand().trim() + " " : "")
219
		+ ((item.getModelName() != null) ? item.getModelName().trim() + " " : "")
220
		+ (( item.getModelNumber() != null ) ? item.getModelNumber().trim() : "" );
2561 rajveer 221
		title = title.replaceAll("  ", " ");
2367 rajveer 222
		return title;
223
	}
224
 
225
	/**
1678 rajveer 226
	 * get xml feed for partner sites
227
	 * @param irDataXMLSnippets
228
	 * @throws Exception
229
	 */
2367 rajveer 230
	private void getProductsXML(ArrayList<String> irDataXMLSnippets) throws Exception{
5113 amit.gupta 231
		LogisticsService.Client prod_client = null;
5350 varun.gupt 232
		Map<Long, ItemCouponDiscount> couponsAndDiscounts = new HashMap<Long, ItemCouponDiscount>();
233
 
5113 amit.gupta 234
		try {
5350 varun.gupt 235
 
236
			List<Long> itemIds = new ArrayList<Long>();
237
 
238
			for(Long entityId: entityIdItemMap.keySet()){
239
 
240
				List<Item> items = entityIdItemMap.get(entityId);
241
				Item firstItem = items.get(0);
242
 
6720 amit.gupta 243
				if(!firstItem.getItemStatus().equals(status.COMING_SOON) && isMobile(firstItem) || isLaptop(firstItem)) {
5350 varun.gupt 244
					itemIds.add(firstItem.getId());
245
				}
246
			}
247
 
248
			PromotionClient promotionClient = new PromotionClient();
249
			in.shop2020.model.v1.user.PromotionService.Client promotionServiceClient = promotionClient.getClient();
250
 
251
			List<ItemCouponDiscount> itemsCouponsAndDiscounts = promotionServiceClient.getItemDiscountMap(itemIds);
252
 
253
			for (ItemCouponDiscount itemCouponDiscount: itemsCouponsAndDiscounts) {
254
				couponsAndDiscounts.put(itemCouponDiscount.getItemId(), itemCouponDiscount);
255
			}
6625 amit.gupta 256
 
257
			LogisticsClient logistics_prod = new LogisticsClient("logistics_service_prod_server_host","logistics_service_prod_server_port");
258
			prod_client = logistics_prod.getClient();
5350 varun.gupt 259
 
5113 amit.gupta 260
		} catch (Exception e) {
261
			prod_client = null;
5350 varun.gupt 262
			Utils.info("Logistics estimations can't be fetched as Logistics Service is inaccessible" + e);
5113 amit.gupta 263
		}
5350 varun.gupt 264
 
2367 rajveer 265
		for(Long entityId: entityIdItemMap.keySet()){
266
			List<Item> items = entityIdItemMap.get(entityId);
267
			Item firstItem = items.get(0);
5229 varun.gupt 268
 
6720 amit.gupta 269
			if((firstItem.getItemStatus().equals(status.COMING_SOON) && !firstItem.isShowSellingPrice()) || !isMobile(firstItem) && !isTablet(firstItem))	{
1678 rajveer 270
				continue;
271
			}
272
 
273
			irDataXMLSnippets.add(this.xmlIndentation[1] + "<products>");	
274
 
2367 rajveer 275
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
1678 rajveer 276
 
2367 rajveer 277
			String title = getProductTitle(firstItem);
1678 rajveer 278
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + title + "</ProductName>");
279
 
2367 rajveer 280
			String url = getProductURL(entityId, firstItem);
3929 mandeep.dh 281
 
282
			String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator +
283
			                  "website" + File.separator + entityId + File.separator + "icon.jpg";
284
 
1678 rajveer 285
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + url + "</ProductURL>");
6602 amit.gupta 286
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<Availability>" + (inStockCatalogItemIds.contains(entityId) ? "Y" : "N") + "</Availability>");
5350 varun.gupt 287
			double minPrice = getMinPrice(items);
1678 rajveer 288
 
5350 varun.gupt 289
			if(couponsAndDiscounts.containsKey(firstItem.getId()))	{
290
 
291
				int discountedPrice = (int)(minPrice - couponsAndDiscounts.get(firstItem.getId()).getDiscount());
292
				irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductPrice>" + discountedPrice + "</ProductPrice>");
293
 
294
			} else	{
295
				irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductPrice>" + minPrice + "</ProductPrice>");
296
			}
297
 
7034 amit.gupta 298
			if (StringUtils.isNotEmpty(firstItem.getBestDealText())) {
7110 amit.gupta 299
				irDataXMLSnippets.add(this.xmlIndentation[2] + "<DealText>" + StringEscapeUtils.escapeXml(firstItem.getBestDealText()) + "</DealText>");
7034 amit.gupta 300
			}
301
 
3964 rajveer 302
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + getMinMRP(items) + "</ProductMRP>");
303
 
5113 amit.gupta 304
			LogisticsInfo logisticsInfo = null;
305
			if(prod_client != null){
306
				try {
307
					Long itemId = prod_client.getEntityLogisticsEstimation(
308
							entityId, DEFAULT_PINCODE, DeliveryType.PREPAID)
309
							.get(0);
310
					logisticsInfo = prod_client.getLogisticsEstimation(itemId,
311
							DEFAULT_PINCODE, DeliveryType.PREPAID);
312
					irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductDeliveryEstimate>" + logisticsInfo.getDeliveryTime() + "</ProductDeliveryEstimate>");
313
				} catch (Exception e1) {
314
					Utils.info("Unable to get Estimation for Entity: " + entityId + "\n" + e1);
315
				}
316
			}
2130 rajveer 317
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
318
 
1678 rajveer 319
			irDataXMLSnippets.add(this.xmlIndentation[1] + "</products>");		
320
		}
321
	}
322
 
323
	/**
324
	 * Generate the xml list of all the active phones and store in a file
325
	 * @throws Exception
326
	 */
2227 rajveer 327
	public void generateProductsListXML() throws Exception {
1678 rajveer 328
		ArrayList<String> productXMLSnippets = new ArrayList<String>();
329
		productXMLSnippets.add("<saholic.com>");
330
 
331
		getProductsXML(productXMLSnippets);
332
 
333
		productXMLSnippets.add("</saholic.com>");
334
 
335
		String productDataXML = StringUtils.join(productXMLSnippets, "\n");
336
 
337
		Utils.info(productDataXML);
338
 
339
		// Write it to file
2130 rajveer 340
		String productXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "saholicmobilephones.xml";
1678 rajveer 341
		DBUtils.store(productDataXML, productXMLFilename);
342
	}
2227 rajveer 343
 
5355 varun.gupt 344
	/**
345
	 * Generate the xml list of all the active accessories and store in a file
346
	 * @throws Exception
347
	 */
348
	public void generateAccessoriesXML() throws Exception	{
349
		LogisticsService.Client prod_client = null;
350
 
351
		try	{
352
			LogisticsClient logistics_prod = new LogisticsClient("logistics_service_prod_server_host","logistics_service_prod_server_port");
353
			prod_client = logistics_prod.getClient();
354
 
355
		} catch (Exception e) {
356
			prod_client = null;
357
			Utils.info("Logistics estimations can't be fetched as Logistics Service is inaccessible" + e);
358
		}
359
		List<String> accessoriesXMLSnippets = new ArrayList<String>();
360
 
361
		accessoriesXMLSnippets.add("<saholic.com>");
362
 
363
		for(Long entityId: entityIdItemMap.keySet())	{
364
 
365
			List<Item> items = entityIdItemMap.get(entityId);
366
			Item firstItem = items.get(0);
367
 
368
			if(! isAccessory(firstItem))	{
369
				continue;
370
			}
371
			String title = getProductTitle(firstItem);
372
			String url = getProductURL(entityId, firstItem);
373
			String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator +
374
            "website" + File.separator + entityId + File.separator + "icon.jpg";
375
 
376
			accessoriesXMLSnippets.add(this.xmlIndentation[1] + "<products>");	
377
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
5362 varun.gupt 378
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + StringEscapeUtils.escapeXml(title) + "</ProductName>");
5363 varun.gupt 379
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + StringEscapeUtils.escapeXml(url) + "</ProductURL>");
5355 varun.gupt 380
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductPrice>" + getMinPrice(items) + "</ProductPrice>");
381
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + getMinMRP(items) + "</ProductMRP>");
382
 
383
			LogisticsInfo logisticsInfo = null;
384
			if(prod_client != null){
385
				try {
386
					Long itemId = prod_client.getEntityLogisticsEstimation(entityId, DEFAULT_PINCODE, DeliveryType.PREPAID).get(0);
387
					logisticsInfo = prod_client.getLogisticsEstimation(itemId, DEFAULT_PINCODE, DeliveryType.PREPAID);
388
					accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductDeliveryEstimate>" + logisticsInfo.getDeliveryTime() + "</ProductDeliveryEstimate>");
389
				} catch (Exception e1) {
390
					Utils.info("Unable to get Estimation for Entity: " + entityId + "\n" + e1);
391
				}
392
			}
393
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
394
			accessoriesXMLSnippets.add(this.xmlIndentation[1] + "</products>");		
395
		}
396
 
397
		accessoriesXMLSnippets.add("</saholic.com>");
2227 rajveer 398
 
5355 varun.gupt 399
		String accessoriesXML = StringUtils.join(accessoriesXMLSnippets, "\n");
400
 
401
		Utils.info(accessoriesXML);
402
 
403
		// Write it to file
404
		String accessoriesXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "saholicaccessories.xml";
405
		DBUtils.store(accessoriesXML, accessoriesXMLFilename);
406
	}
2227 rajveer 407
 
5935 amit.gupta 408
 
409
 
2227 rajveer 410
	/**
5935 amit.gupta 411
	 * Generate the xml list of all the active cameras and store in a file
412
	 * @throws Exception
413
	 */
414
	public void generateCamerasXML() throws Exception	{
415
		LogisticsService.Client prod_client = null;
416
 
417
		try	{
418
			LogisticsClient logistics_prod = new LogisticsClient("logistics_service_prod_server_host","logistics_service_prod_server_port");
419
			prod_client = logistics_prod.getClient();
420
 
421
		} catch (Exception e) {
422
			prod_client = null;
423
			Utils.info("Logistics estimations can't be fetched as Logistics Service is inaccessible" + e);
424
		}
425
		List<String> camerasXMLSnippets = new ArrayList<String>();
426
 
427
		camerasXMLSnippets.add("<saholic.com>");
428
 
429
		for(Long entityId: entityIdItemMap.keySet())	{
430
 
431
			List<Item> items = entityIdItemMap.get(entityId);
432
			Item firstItem = items.get(0);
433
 
434
			if(! isCamera(firstItem))	{
435
				continue;
436
			}
437
			String title = getProductTitle(firstItem);
438
			String url = getProductURL(entityId, firstItem);
439
			String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator +
440
			"website" + File.separator + entityId + File.separator + "icon.jpg";
441
 
442
			camerasXMLSnippets.add(this.xmlIndentation[1] + "<products>");	
443
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
444
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + StringEscapeUtils.escapeXml(title) + "</ProductName>");
445
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + StringEscapeUtils.escapeXml(url) + "</ProductURL>");
446
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductPrice>" + getMinPrice(items) + "</ProductPrice>");
447
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + getMinMRP(items) + "</ProductMRP>");
6602 amit.gupta 448
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<Availability>" + (inStockCatalogItemIds.contains(entityId) ? "Y" : "N") + "</Availability>");
5935 amit.gupta 449
 
450
			LogisticsInfo logisticsInfo = null;
451
			if(prod_client != null){
452
				try {
453
					Long itemId = prod_client.getEntityLogisticsEstimation(entityId, DEFAULT_PINCODE, DeliveryType.PREPAID).get(0);
454
					logisticsInfo = prod_client.getLogisticsEstimation(itemId, DEFAULT_PINCODE, DeliveryType.PREPAID);
455
					camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductDeliveryEstimate>" + logisticsInfo.getDeliveryTime() + "</ProductDeliveryEstimate>");
456
				} catch (Exception e1) {
457
					Utils.info("Unable to get Estimation for Entity: " + entityId + "\n" + e1);
458
				}
459
			}
460
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
461
			camerasXMLSnippets.add(this.xmlIndentation[1] + "</products>");		
462
		}
463
 
464
		camerasXMLSnippets.add("</saholic.com>");
465
 
466
		String camerasXML = StringUtils.join(camerasXMLSnippets, "\n");
467
 
468
		Utils.info(camerasXML);
469
 
470
		// Write it to file
471
		String accessoriesXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "saholiccameras.xml";
472
		DBUtils.store(camerasXML, accessoriesXMLFilename);
473
	}
474
 
475
	/**
2227 rajveer 476
	 * get xml feed for partner sites
477
	 * @param irDataXMLSnippets
478
	 * @throws Exception
479
	 */
480
	private void getProductsJavascript(StringBuffer sb) throws Exception{
4143 varun.gupt 481
 
5347 amit.gupta 482
		Map<String, Map<String, Long>> products = new HashMap<String, Map<String,Long>>();
2367 rajveer 483
 
5347 amit.gupta 484
		for(Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet())	{
485
			Item item = entry.getValue().get(0);
5930 amit.gupta 486
			in.shop2020.metamodel.definitions.Category category = defContainer.getCategory(item.getCategory());
487
			in.shop2020.metamodel.definitions.Category parentCategory = category.getParentCategory();
488
			String categoryLabel = category.getLabel();
5347 amit.gupta 489
			if(parentCategory.isComparable()){
5930 amit.gupta 490
				categoryLabel = parentCategory.getLabel();
2227 rajveer 491
			}
5930 amit.gupta 492
			if(!products.containsKey(categoryLabel)){
493
				Map<String, Long> catMap = new HashMap<String, Long>();
494
				products.put(categoryLabel, catMap);
495
			}
496
			products.get(categoryLabel).put(getProductTitle(item), entry.getKey());
2227 rajveer 497
		}
4143 varun.gupt 498
		sb.append(new JSONObject(products));
2227 rajveer 499
	}
500
 
501
 
502
	/**
503
	 * Generate the javascript list of all the active phones and store in a file
504
	 * @throws Exception
505
	 */
506
	public void generateProductListJavascript() throws Exception {
507
		StringBuffer productsJavascript = new StringBuffer();
508
 
4143 varun.gupt 509
		productsJavascript.append("var productIdNames=");
2227 rajveer 510
 
511
		getProductsJavascript(productsJavascript);
512
 
4143 varun.gupt 513
		productsJavascript.append(";");
2227 rajveer 514
 
515
		// Write it to file
516
		String productXMLFilename = Utils.EXPORT_JAVASCRIPT_CONTENT_PATH + "saholicmobilephones.js";
517
		DBUtils.store(productsJavascript.toString(), productXMLFilename);
518
	}
4188 varun.gupt 519
 
520
    private void populateEntityIdItemMap(List<Item> items){
7630 amit.gupta 521
    	entityIdItemMap = new HashMap<Long, List<Item>>(); 
4188 varun.gupt 522
        for(Item item: items){
523
            //TODO Can be removed as we are checking in calling function
7629 amit.gupta 524
            if(!(item.getItemStatus()==status.ACTIVE || item.getItemStatus() == status.PAUSED)){
4188 varun.gupt 525
                continue;
526
            }
7629 amit.gupta 527
            if( item.getSellingPrice() == 0){
4188 varun.gupt 528
                continue;
529
            }
530
            List<Item> itemList = entityIdItemMap.get(item.getCatalogItemId());
531
            if(itemList == null){
532
                itemList = new ArrayList<Item>();
533
            }
534
            itemList.add(item);
535
            entityIdItemMap.put(item.getCatalogItemId(), itemList);
536
        }
537
    }
5229 varun.gupt 538
 
539
    /**
540
     * Generate XML feed for mobile site
541
     * @throws Exception
542
     */
543
    public void generateXMLFeedForMobileSite() throws Exception	{
544
    	List<String> productXMLSnippets = new ArrayList<String>();
545
		productXMLSnippets.add("<Products>");
546
		List<Long> itemIds = new ArrayList<Long>();
547
 
548
		for(Long entityId: entityIdItemMap.keySet()){
549
			List<Item> items = entityIdItemMap.get(entityId);
550
			Item firstItem = items.get(0);
551
			Utils.info("first Item: " + firstItem);
552
 
553
			if(isMobile(firstItem) || isLaptop(firstItem)) {
554
				itemIds.add(firstItem.getId());
555
			}
556
		}
4188 varun.gupt 557
 
5229 varun.gupt 558
		List<String> descriptions = new ArrayList<String>();
559
		descriptions.add("8MP camera, Super AMOLED Plus display, Android Gingerbread");
560
		descriptions.add("Android OS v2.2 Froyo, 800MHz processor, 3.5\" capacitive display");
561
		descriptions.add("Dual-SIM, Wi-Fi, Bluetooth, Social networking &amp; IM");
562
		descriptions.add("Android Gingerbread, Facebook button, 5MP camera");
563
		descriptions.add("Android Gingerbread, 1GHz processor, 3.7\" Gorilla Glass display");
564
		descriptions.add("2GB RAM, 500GB HDD, Intel Core 2 Duo T6570 processor, DOS");
565
		descriptions.add("4GB RAM, 500GB HDD, Intel Core i5 2410M processor, Windows 7 Basic");
566
		descriptions.add("3.2\" touchscreen, 2MP camera, IM &amp; social networking");
567
 
568
		for(Long entityId: entityIdItemMap.keySet()) {
569
			List<Item> items = entityIdItemMap.get(entityId);
570
			Item firstItem = items.get(0);
571
 
572
			if(!isMobile(firstItem) && !isLaptop(firstItem)){
573
				continue;
574
			}
4188 varun.gupt 575
 
5229 varun.gupt 576
			String url = getProductURL(entityId, firstItem);
577
			String imageUrl = "http://www.saholic.com/images/website" + File.separator + entityId + File.separator + "thumbnail.jpg";
578
			String description = descriptions.get((int) (8 * Math.random()));
579
			double minPrice = getMinPrice(items);
580
 
581
			String productType = "";
582
 
8749 amit.gupta 583
			if (firstItem.getCategory() == 10006)	{
5229 varun.gupt 584
				productType = "Mobile Phone";
585
 
586
			} else if (firstItem.getCategory() == 10010)	{
587
				productType = "Tablet";
588
 
589
			} else if (firstItem.getCategory() == 10050)	{
590
				productType = "Laptop";
591
			}
592
 
593
			productXMLSnippets.add(this.xmlIndentation[1] + "<Product>");	
594
 
595
			productXMLSnippets.add(this.xmlIndentation[2] + "<ID>" + entityId + "</ID>");
596
			productXMLSnippets.add(this.xmlIndentation[2] + "<Type>" + productType + "</Type>");
597
			productXMLSnippets.add(this.xmlIndentation[2] + "<Brand>" + firstItem.getBrand() + "</Brand>");
598
			productXMLSnippets.add(this.xmlIndentation[2] + "<ModelName>" + firstItem.getModelName() + "</ModelName>");
599
			productXMLSnippets.add(this.xmlIndentation[2] + "<ModelNumber>" + firstItem.getModelNumber() + "</ModelNumber>");
600
			productXMLSnippets.add(this.xmlIndentation[2] + "<URL>" + url + "</URL>");
601
			productXMLSnippets.add(this.xmlIndentation[2] + "<ImageURL>" + imageUrl + "</ImageURL>");
602
			productXMLSnippets.add(this.xmlIndentation[2] + "<ShortDesc>" + description + "</ShortDesc>");
603
			productXMLSnippets.add(this.xmlIndentation[2] + "<MRP>" + firstItem.getMrp() + "</MRP>");
604
			productXMLSnippets.add(this.xmlIndentation[2] + "<SellingPrice>" + (int)minPrice  + "</SellingPrice>");
605
 
606
			productXMLSnippets.add(this.xmlIndentation[1] + "</Product>");
607
		}
608
 
609
		productXMLSnippets.add("</Products>");
610
 
611
		String productDataXML = StringUtils.join(productXMLSnippets, "\n");
612
 
613
		Utils.info(productDataXML);
614
 
615
		// Write it to file
616
		String productXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "msitedata.xml";
617
		DBUtils.store(productDataXML, productXMLFilename);
618
    }
619
 
4188 varun.gupt 620
	/**
621
	 * Generate the xml list of all the active phones and store in a file
622
	 * @throws Exception
623
	 */
624
	public void generateProductXMLForDisplayAds() throws Exception {
4384 varun.gupt 625
		Utils.info("Generating Product XML for display ads");
4188 varun.gupt 626
		List<String> productXMLSnippets = new ArrayList<String>();
627
		productXMLSnippets.add("<saholic.com>");
628
		List<Long> itemIds = new ArrayList<Long>();
4384 varun.gupt 629
 
630
		Utils.info("Entity Ids: " + entityIdItemMap.keySet());
4188 varun.gupt 631
 
632
		for(Long entityId: entityIdItemMap.keySet()){
633
			List<Item> items = entityIdItemMap.get(entityId);
634
			Item firstItem = items.get(0);
4384 varun.gupt 635
			Utils.info("first Item: " + firstItem);
636
 
4383 varun.gupt 637
			if(isMobile(firstItem) || isLaptop(firstItem)) {
4188 varun.gupt 638
				itemIds.add(firstItem.getId());
639
			}
640
		}
641
 
642
		PromotionClient promotionClient = new PromotionClient();
643
		in.shop2020.model.v1.user.PromotionService.Client promotionServiceClient = promotionClient.getClient();
644
 
645
		List<ItemCouponDiscount> itemsCouponsAndDiscounts = promotionServiceClient.getItemDiscountMap(itemIds);
646
 
647
		Map<Long, ItemCouponDiscount> couponsAndDiscounts = new HashMap<Long, ItemCouponDiscount>();
648
 
649
		for (ItemCouponDiscount itemCouponDiscount: itemsCouponsAndDiscounts) {
650
			couponsAndDiscounts.put(itemCouponDiscount.getItemId(), itemCouponDiscount);
651
		}
4384 varun.gupt 652
		Utils.info("Entity IDs: " + entityIdItemMap.keySet());
4188 varun.gupt 653
 
654
		for(Long entityId: entityIdItemMap.keySet()) {
655
			List<Item> items = entityIdItemMap.get(entityId);
656
			Item firstItem = items.get(0);
4384 varun.gupt 657
 
658
			Utils.info("First Item: " + firstItem);
659
 
4382 varun.gupt 660
			if(!isMobile(firstItem) && !isLaptop(firstItem)){
4188 varun.gupt 661
				continue;
662
			}
663
 
664
			productXMLSnippets.add(this.xmlIndentation[1] + "<products>");	
665
 
666
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
667
 
668
			String title = getProductTitle(firstItem);
669
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + title + "</ProductName>");
670
 
671
			String url = getProductURL(entityId, firstItem);
672
 
673
			String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator + entityId + File.separator + "icon.jpg";    
674
 
675
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + url + "</ProductURL>");
676
 
677
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
678
 
679
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + firstItem.getMrp() + "</ProductMRP>");
680
 
681
			double minPrice = getMinPrice(items);
682
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductSellingPrice>" + (int)minPrice  + "</ProductSellingPrice>");
6602 amit.gupta 683
			productXMLSnippets.add(this.xmlIndentation[2] + "<Availability>" + (inStockCatalogItemIds.contains(entityId) ? "Y" : "N") + "</Availability>");
4188 varun.gupt 684
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductDiscount>" + (int)((firstItem.getMrp()-minPrice)/firstItem.getMrp()*100) + "</ProductDiscount>");
685
 
686
			long itemId = firstItem.getId();
687
 
688
			if(couponsAndDiscounts.containsKey(itemId))	{
689
 
690
				ItemCouponDiscount itemCouponDiscount = couponsAndDiscounts.get(itemId);
691
 
692
				productXMLSnippets.add(this.xmlIndentation[2] + "<ProductCoupons>");
693
				productXMLSnippets.add(this.xmlIndentation[3] + "<Coupon>");
694
				productXMLSnippets.add(this.xmlIndentation[4] + "<CouponCode>" + itemCouponDiscount.getCouponCode() + "</CouponCode>");
695
				productXMLSnippets.add(this.xmlIndentation[4] + "<PriceAfterCoupon>" + (int)(minPrice - itemCouponDiscount.getDiscount()) + "</PriceAfterCoupon>");
696
				productXMLSnippets.add(this.xmlIndentation[3] + "</Coupon>");
697
				productXMLSnippets.add(this.xmlIndentation[2] + "</ProductCoupons>");
698
 
699
			} else	{
700
				productXMLSnippets.add(this.xmlIndentation[2] + "<ProductCoupons />");
701
			}
702
 
703
			String description = "";
704
			Entity entity = CreationUtils.getEntity(entityId);
705
			if(entity!=null){
706
				if(entity.getSlide(130001) !=null){
4202 varun.gupt 707
					description = StringEscapeUtils.escapeXml(entity.getSlide(130001).getFreeformContent().getFreeformText());
4188 varun.gupt 708
				}
709
			}
710
 
711
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductDescription>" + description + "</ProductDescription>");
712
 
713
			productXMLSnippets.add(this.xmlIndentation[1] + "</products>");	
714
		}
715
 
716
		productXMLSnippets.add("</saholic.com>");
717
 
718
		String productDataXML = StringUtils.join(productXMLSnippets, "\n");
719
 
720
		Utils.info(productDataXML);
721
 
722
		// Write it to file
723
		String productXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "advertismentapi.xml";
724
		DBUtils.store(productDataXML, productXMLFilename);
725
	}
5229 varun.gupt 726
 
8143 amit.gupta 727
	public static void main(String[] args) {
728
			try {
7506 amit.gupta 729
			CatalogClient cl = new CatalogClient();
730
			in.shop2020.model.v1.catalog.CatalogService.Client client = cl.getClient();
7629 amit.gupta 731
			List<Item> items = client.getAllItemsByStatus(status.ACTIVE);
732
			items.addAll(client.getAllItemsByStatus(status.PAUSED));
733
			ProductListGenerator generator = new ProductListGenerator(items);
7506 amit.gupta 734
 
735
        	log.info("Before thinkdigit feed.");
736
        	generator.generateThinkDigitFeed();
5229 varun.gupt 737
 
7506 amit.gupta 738
 
739
    		log.info("Before product list xml.");
740
        	generator.generateProductsListXML();
741
 
742
        	log.info("Before product accessories xml.");
743
        	generator.generateAccessoriesXML();
744
 
745
        	log.info("Before product camera xml.");
746
        	generator.generateCamerasXML();
747
 
748
        	log.info("Before product display ads.");
8143 amit.gupta 749
			} catch (Exception ex){
750
				String logfile = "/tmp/content-from-cms.log";
751
				 GmailUtils gm = new GmailUtils();
752
			        String[] sendTo = { "rajveer.singh@shop2020.in", "anupam.singh@shop2020.in", "amit.gupta@shop2020.in" };
753
 
754
			        try {
755
			            gm.sendSSLMessage(sendTo, "Partners feed generation failed", ""
756
			                    + Calendar.getInstance().getTime().toString(),
757
			                    "build@shop2020.in", "cafe@nes", logfile);
758
			        } catch (MessagingException e) {
759
			            log.error("Could not send status mail", e);
760
			        }
761
			}
7506 amit.gupta 762
    		//generator.generateProductXMLForDisplayAds();
5229 varun.gupt 763
	}
5612 amit.gupta 764
 
765
    private String readFile(String path) throws IOException {
766
		FileInputStream stream = new FileInputStream(new File(path));
767
		try {
768
			FileChannel fc = stream.getChannel();
769
			MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()-1);
770
			/* Instead of using default, pass in a decoder. */
771
			return Charset.defaultCharset().decode(bb).toString();
772
		}
773
		finally {
774
			stream.close();
775
		}
776
	}
6025 amit.gupta 777
    /**
778
     * Feed generated for thinkdigit that only contains the live items
779
     * feed should have s
780
     */
781
    public void generateThinkDigitFeed() throws Exception{
782
 
7837 amit.gupta 783
    	List<Long> riskyPausedItems = this.getRiskyPausedItems();
6025 amit.gupta 784
    	List<String> productXMLSnippets = new ArrayList<String>();
785
    	productXMLSnippets.add("<root>");
786
    	String thinkDigitFeedFileName = Utils.EXPORT_PARTNERS_CONTENT_PATH + "all-categories.xml";
6624 rajveer 787
    	for (Long entityId : entityIdItemMap.keySet()){
788
    		List<Item> items = entityIdItemMap.get(entityId);
7373 amit.gupta 789
    		long cate = items.get(0).getCategory();
7374 amit.gupta 790
 
791
    		Utils.info(items.get(0).getId() + ","  + String.valueOf(cate));
7373 amit.gupta 792
    		Category category = Catalog.getInstance().getDefinitionsContainer().getCategory(cate);
793
    		Category parentCategory = category.getParentCategory(); 
7837 amit.gupta 794
            for(Item item: items){
795
            	if(item.getItemStatus().equals(status.ACTIVE)) {
796
            		if(!(item.isRisky() && riskyPausedItems.contains(item.getId()) )){
797
            			inStockCatalogItemIds.add(entityId);
798
            			if(validParentCategories.contains(parentCategory.getID())) { 
799
            				productXMLSnippets.add(this.xmlIndentation[1] + "<products>");
800
            				productXMLSnippets.add(this.xmlIndentation[2] + "<id>" + item.getCatalogItemId() + "</id>");
801
            				productXMLSnippets.add(this.xmlIndentation[2] + "<product>" + getProductTitle(item) + "</product>");
802
            				productXMLSnippets.add(this.xmlIndentation[2] + "<Product_URL>" + getProductURL(item.getCatalogItemId(), item, 59) + "</Product_URL>");
803
            				productXMLSnippets.add(this.xmlIndentation[2] + "<Product_Price>" + (int)item.getSellingPrice() + "</Product_Price>");
804
            				productXMLSnippets.add(this.xmlIndentation[2] + "<Merchant_Name>" + "saholic.com" + "</Merchant_Name>");
805
            				productXMLSnippets.add(this.xmlIndentation[2] + "<Category_Name>" + parentCategory.getLabel() + "</Category_Name>");
806
            				productXMLSnippets.add(this.xmlIndentation[1] + "</products>");
807
            			}
808
            			break;
809
            		}
810
            	}
811
            }
6025 amit.gupta 812
    	}
813
    	productXMLSnippets.add("</root>");
814
    	String productDataXML = StringUtils.join(productXMLSnippets, "\n");
815
    	DBUtils.store(productDataXML, thinkDigitFeedFileName);
816
 
817
    }
6257 rajveer 818
 
819
    public static void updatePriceForEntity(long catalogItemId, double sp, double mrp){
820
    	try{
821
    		String filename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "saholicmobilephones.xml";
822
    		File file = new File(filename);
823
    		if (file.exists()){
824
    			DOMParser parser = new DOMParser();
825
    			parser.parse(filename);
826
    			Document doc = parser.getDocument();
827
    			NodeList list = doc.getElementsByTagName("ProductSKU");
828
    			for(int i=0; i<list.getLength(); i++){
829
    				if(list.item(i).getTextContent().equals(catalogItemId+"")){
830
    					Node spNode = doc.getElementsByTagName("ProductPrice").item(i);
831
    					spNode.setTextContent(sp+"");
832
    					Node mrpNode = doc.getElementsByTagName("ProductMRP").item(i);
833
    					mrpNode.setTextContent(mrp+"");
834
    				}
835
    			}
836
    			writeXmlFile(doc, filename);
837
    		}
838
    		else{
839
    			System.out.println("File not found!");
840
    		}
841
    	}
842
    	catch (Exception e){
843
    		e.getMessage();
844
    	}
845
    }
846
 
847
    // This method writes a DOM document to a file
848
    public static void writeXmlFile(Document doc, String filename) {
849
    	try {
850
    		// Prepare the DOM document for writing
851
    		Source source = new DOMSource(doc);
852
 
853
    		// Prepare the output file
854
    		File file = new File(filename);
855
    		Result result = new StreamResult(file);
856
 
857
    		// Write the DOM document to the file
858
    		Transformer xformer = TransformerFactory.newInstance().newTransformer();
859
    		xformer.transform(source, result);
860
    	} catch (TransformerConfigurationException e) {
861
    	} catch (TransformerException e) {
862
    	}
863
    }
7837 amit.gupta 864
 
865
    private List<Long> getRiskyPausedItems() {
866
		try {
867
			Reader reader = new FileReader(Utils.EXPORT_PATH + Utils.RISKY_PAUSED_JSON);
868
			return new Gson().fromJson(reader, new TypeToken<List<Long>>() {}.getType());
869
		} catch (FileNotFoundException e) {
870
			log.error("Could not read paused file");
871
			e.printStackTrace();
872
			return new ArrayList<Long>();
873
		}
874
	}
4143 varun.gupt 875
}