Subversion Repositories SmartDukaan

Rev

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