Subversion Repositories SmartDukaan

Rev

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