Subversion Repositories SmartDukaan

Rev

Rev 7110 | Rev 7374 | 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 {
5350 varun.gupt 233
 
234
			List<Long> itemIds = new ArrayList<Long>();
235
 
236
			for(Long entityId: entityIdItemMap.keySet()){
237
 
238
				List<Item> items = entityIdItemMap.get(entityId);
239
				Item firstItem = items.get(0);
240
 
6720 amit.gupta 241
				if(!firstItem.getItemStatus().equals(status.COMING_SOON) && isMobile(firstItem) || isLaptop(firstItem)) {
5350 varun.gupt 242
					itemIds.add(firstItem.getId());
243
				}
244
			}
245
 
246
			PromotionClient promotionClient = new PromotionClient();
247
			in.shop2020.model.v1.user.PromotionService.Client promotionServiceClient = promotionClient.getClient();
248
 
249
			List<ItemCouponDiscount> itemsCouponsAndDiscounts = promotionServiceClient.getItemDiscountMap(itemIds);
250
 
251
			for (ItemCouponDiscount itemCouponDiscount: itemsCouponsAndDiscounts) {
252
				couponsAndDiscounts.put(itemCouponDiscount.getItemId(), itemCouponDiscount);
253
			}
6625 amit.gupta 254
 
255
			LogisticsClient logistics_prod = new LogisticsClient("logistics_service_prod_server_host","logistics_service_prod_server_port");
256
			prod_client = logistics_prod.getClient();
5350 varun.gupt 257
 
5113 amit.gupta 258
		} catch (Exception e) {
259
			prod_client = null;
5350 varun.gupt 260
			Utils.info("Logistics estimations can't be fetched as Logistics Service is inaccessible" + e);
5113 amit.gupta 261
		}
5350 varun.gupt 262
 
2367 rajveer 263
		for(Long entityId: entityIdItemMap.keySet()){
264
			List<Item> items = entityIdItemMap.get(entityId);
265
			Item firstItem = items.get(0);
5229 varun.gupt 266
 
6720 amit.gupta 267
			if((firstItem.getItemStatus().equals(status.COMING_SOON) && !firstItem.isShowSellingPrice()) || !isMobile(firstItem) && !isTablet(firstItem))	{
1678 rajveer 268
				continue;
269
			}
270
 
271
			irDataXMLSnippets.add(this.xmlIndentation[1] + "<products>");	
272
 
2367 rajveer 273
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
1678 rajveer 274
 
2367 rajveer 275
			String title = getProductTitle(firstItem);
1678 rajveer 276
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + title + "</ProductName>");
277
 
2367 rajveer 278
			String url = getProductURL(entityId, firstItem);
3929 mandeep.dh 279
 
280
			String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator +
281
			                  "website" + File.separator + entityId + File.separator + "icon.jpg";
282
 
1678 rajveer 283
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + url + "</ProductURL>");
6602 amit.gupta 284
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<Availability>" + (inStockCatalogItemIds.contains(entityId) ? "Y" : "N") + "</Availability>");
5350 varun.gupt 285
			double minPrice = getMinPrice(items);
1678 rajveer 286
 
5350 varun.gupt 287
			if(couponsAndDiscounts.containsKey(firstItem.getId()))	{
288
 
289
				int discountedPrice = (int)(minPrice - couponsAndDiscounts.get(firstItem.getId()).getDiscount());
290
				irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductPrice>" + discountedPrice + "</ProductPrice>");
291
 
292
			} else	{
293
				irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductPrice>" + minPrice + "</ProductPrice>");
294
			}
295
 
7034 amit.gupta 296
			if (StringUtils.isNotEmpty(firstItem.getBestDealText())) {
7110 amit.gupta 297
				irDataXMLSnippets.add(this.xmlIndentation[2] + "<DealText>" + StringEscapeUtils.escapeXml(firstItem.getBestDealText()) + "</DealText>");
7034 amit.gupta 298
			}
299
 
3964 rajveer 300
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + getMinMRP(items) + "</ProductMRP>");
301
 
5113 amit.gupta 302
			LogisticsInfo logisticsInfo = null;
303
			if(prod_client != null){
304
				try {
305
					Long itemId = prod_client.getEntityLogisticsEstimation(
306
							entityId, DEFAULT_PINCODE, DeliveryType.PREPAID)
307
							.get(0);
308
					logisticsInfo = prod_client.getLogisticsEstimation(itemId,
309
							DEFAULT_PINCODE, DeliveryType.PREPAID);
310
					irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductDeliveryEstimate>" + logisticsInfo.getDeliveryTime() + "</ProductDeliveryEstimate>");
311
				} catch (Exception e1) {
312
					Utils.info("Unable to get Estimation for Entity: " + entityId + "\n" + e1);
313
				}
314
			}
2130 rajveer 315
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
316
 
1678 rajveer 317
			irDataXMLSnippets.add(this.xmlIndentation[1] + "</products>");		
318
		}
319
	}
320
 
321
	/**
322
	 * Generate the xml list of all the active phones and store in a file
323
	 * @throws Exception
324
	 */
2227 rajveer 325
	public void generateProductsListXML() throws Exception {
1678 rajveer 326
		ArrayList<String> productXMLSnippets = new ArrayList<String>();
327
		productXMLSnippets.add("<saholic.com>");
328
 
329
		getProductsXML(productXMLSnippets);
330
 
331
		productXMLSnippets.add("</saholic.com>");
332
 
333
		String productDataXML = StringUtils.join(productXMLSnippets, "\n");
334
 
335
		Utils.info(productDataXML);
336
 
337
		// Write it to file
2130 rajveer 338
		String productXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "saholicmobilephones.xml";
1678 rajveer 339
		DBUtils.store(productDataXML, productXMLFilename);
340
	}
2227 rajveer 341
 
5355 varun.gupt 342
	/**
343
	 * Generate the xml list of all the active accessories and store in a file
344
	 * @throws Exception
345
	 */
346
	public void generateAccessoriesXML() throws Exception	{
347
		LogisticsService.Client prod_client = null;
348
 
349
		try	{
350
			LogisticsClient logistics_prod = new LogisticsClient("logistics_service_prod_server_host","logistics_service_prod_server_port");
351
			prod_client = logistics_prod.getClient();
352
 
353
		} catch (Exception e) {
354
			prod_client = null;
355
			Utils.info("Logistics estimations can't be fetched as Logistics Service is inaccessible" + e);
356
		}
357
		List<String> accessoriesXMLSnippets = new ArrayList<String>();
358
 
359
		accessoriesXMLSnippets.add("<saholic.com>");
360
 
361
		for(Long entityId: entityIdItemMap.keySet())	{
362
 
363
			List<Item> items = entityIdItemMap.get(entityId);
364
			Item firstItem = items.get(0);
365
 
366
			if(! isAccessory(firstItem))	{
367
				continue;
368
			}
369
			String title = getProductTitle(firstItem);
370
			String url = getProductURL(entityId, firstItem);
371
			String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator +
372
            "website" + File.separator + entityId + File.separator + "icon.jpg";
373
 
374
			accessoriesXMLSnippets.add(this.xmlIndentation[1] + "<products>");	
375
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
5362 varun.gupt 376
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + StringEscapeUtils.escapeXml(title) + "</ProductName>");
5363 varun.gupt 377
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + StringEscapeUtils.escapeXml(url) + "</ProductURL>");
5355 varun.gupt 378
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductPrice>" + getMinPrice(items) + "</ProductPrice>");
379
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + getMinMRP(items) + "</ProductMRP>");
380
 
381
			LogisticsInfo logisticsInfo = null;
382
			if(prod_client != null){
383
				try {
384
					Long itemId = prod_client.getEntityLogisticsEstimation(entityId, DEFAULT_PINCODE, DeliveryType.PREPAID).get(0);
385
					logisticsInfo = prod_client.getLogisticsEstimation(itemId, DEFAULT_PINCODE, DeliveryType.PREPAID);
386
					accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductDeliveryEstimate>" + logisticsInfo.getDeliveryTime() + "</ProductDeliveryEstimate>");
387
				} catch (Exception e1) {
388
					Utils.info("Unable to get Estimation for Entity: " + entityId + "\n" + e1);
389
				}
390
			}
391
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
392
			accessoriesXMLSnippets.add(this.xmlIndentation[1] + "</products>");		
393
		}
394
 
395
		accessoriesXMLSnippets.add("</saholic.com>");
2227 rajveer 396
 
5355 varun.gupt 397
		String accessoriesXML = StringUtils.join(accessoriesXMLSnippets, "\n");
398
 
399
		Utils.info(accessoriesXML);
400
 
401
		// Write it to file
402
		String accessoriesXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "saholicaccessories.xml";
403
		DBUtils.store(accessoriesXML, accessoriesXMLFilename);
404
	}
2227 rajveer 405
 
5935 amit.gupta 406
 
407
 
2227 rajveer 408
	/**
5935 amit.gupta 409
	 * Generate the xml list of all the active cameras and store in a file
410
	 * @throws Exception
411
	 */
412
	public void generateCamerasXML() throws Exception	{
413
		LogisticsService.Client prod_client = null;
414
 
415
		try	{
416
			LogisticsClient logistics_prod = new LogisticsClient("logistics_service_prod_server_host","logistics_service_prod_server_port");
417
			prod_client = logistics_prod.getClient();
418
 
419
		} catch (Exception e) {
420
			prod_client = null;
421
			Utils.info("Logistics estimations can't be fetched as Logistics Service is inaccessible" + e);
422
		}
423
		List<String> camerasXMLSnippets = new ArrayList<String>();
424
 
425
		camerasXMLSnippets.add("<saholic.com>");
426
 
427
		for(Long entityId: entityIdItemMap.keySet())	{
428
 
429
			List<Item> items = entityIdItemMap.get(entityId);
430
			Item firstItem = items.get(0);
431
 
432
			if(! isCamera(firstItem))	{
433
				continue;
434
			}
435
			String title = getProductTitle(firstItem);
436
			String url = getProductURL(entityId, firstItem);
437
			String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator +
438
			"website" + File.separator + entityId + File.separator + "icon.jpg";
439
 
440
			camerasXMLSnippets.add(this.xmlIndentation[1] + "<products>");	
441
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
442
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + StringEscapeUtils.escapeXml(title) + "</ProductName>");
443
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + StringEscapeUtils.escapeXml(url) + "</ProductURL>");
444
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductPrice>" + getMinPrice(items) + "</ProductPrice>");
445
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + getMinMRP(items) + "</ProductMRP>");
6602 amit.gupta 446
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<Availability>" + (inStockCatalogItemIds.contains(entityId) ? "Y" : "N") + "</Availability>");
5935 amit.gupta 447
 
448
			LogisticsInfo logisticsInfo = null;
449
			if(prod_client != null){
450
				try {
451
					Long itemId = prod_client.getEntityLogisticsEstimation(entityId, DEFAULT_PINCODE, DeliveryType.PREPAID).get(0);
452
					logisticsInfo = prod_client.getLogisticsEstimation(itemId, DEFAULT_PINCODE, DeliveryType.PREPAID);
453
					camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductDeliveryEstimate>" + logisticsInfo.getDeliveryTime() + "</ProductDeliveryEstimate>");
454
				} catch (Exception e1) {
455
					Utils.info("Unable to get Estimation for Entity: " + entityId + "\n" + e1);
456
				}
457
			}
458
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
459
			camerasXMLSnippets.add(this.xmlIndentation[1] + "</products>");		
460
		}
461
 
462
		camerasXMLSnippets.add("</saholic.com>");
463
 
464
		String camerasXML = StringUtils.join(camerasXMLSnippets, "\n");
465
 
466
		Utils.info(camerasXML);
467
 
468
		// Write it to file
469
		String accessoriesXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "saholiccameras.xml";
470
		DBUtils.store(camerasXML, accessoriesXMLFilename);
471
	}
472
 
473
	/**
2227 rajveer 474
	 * get xml feed for partner sites
475
	 * @param irDataXMLSnippets
476
	 * @throws Exception
477
	 */
478
	private void getProductsJavascript(StringBuffer sb) throws Exception{
4143 varun.gupt 479
 
5347 amit.gupta 480
		Map<String, Map<String, Long>> products = new HashMap<String, Map<String,Long>>();
2367 rajveer 481
 
5347 amit.gupta 482
		for(Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet())	{
483
			Item item = entry.getValue().get(0);
5930 amit.gupta 484
			in.shop2020.metamodel.definitions.Category category = defContainer.getCategory(item.getCategory());
485
			in.shop2020.metamodel.definitions.Category parentCategory = category.getParentCategory();
486
			String categoryLabel = category.getLabel();
5347 amit.gupta 487
			if(parentCategory.isComparable()){
5930 amit.gupta 488
				categoryLabel = parentCategory.getLabel();
2227 rajveer 489
			}
5930 amit.gupta 490
			if(!products.containsKey(categoryLabel)){
491
				Map<String, Long> catMap = new HashMap<String, Long>();
492
				products.put(categoryLabel, catMap);
493
			}
494
			products.get(categoryLabel).put(getProductTitle(item), entry.getKey());
2227 rajveer 495
		}
4143 varun.gupt 496
		sb.append(new JSONObject(products));
2227 rajveer 497
	}
498
 
499
 
500
	/**
501
	 * Generate the javascript list of all the active phones and store in a file
502
	 * @throws Exception
503
	 */
504
	public void generateProductListJavascript() throws Exception {
505
		StringBuffer productsJavascript = new StringBuffer();
506
 
4143 varun.gupt 507
		productsJavascript.append("var productIdNames=");
2227 rajveer 508
 
509
		getProductsJavascript(productsJavascript);
510
 
4143 varun.gupt 511
		productsJavascript.append(";");
2227 rajveer 512
 
513
		// Write it to file
514
		String productXMLFilename = Utils.EXPORT_JAVASCRIPT_CONTENT_PATH + "saholicmobilephones.js";
515
		DBUtils.store(productsJavascript.toString(), productXMLFilename);
516
	}
4188 varun.gupt 517
 
518
    private void populateEntityIdItemMap(List<Item> items){
519
        Date toDate = new Date();
520
        for(Item item: items){
521
            //TODO Can be removed as we are checking in calling function
522
            if(!(item.getItemStatus()==status.ACTIVE || item.getItemStatus()==status.CONTENT_COMPLETE || item.getItemStatus() == status.PAUSED)){
523
                continue;
524
            }
525
            if(toDate.getTime() < item.getStartDate() ||  item.getSellingPrice() == 0){
526
                continue;
527
            }
528
            List<Item> itemList = entityIdItemMap.get(item.getCatalogItemId());
529
            if(itemList == null){
530
                itemList = new ArrayList<Item>();
531
            }
532
            itemList.add(item);
533
            entityIdItemMap.put(item.getCatalogItemId(), itemList);
534
        }
535
 
536
        //Remove all items which have not been updated since last content generation.
537
        List<Long> removeEntities = new ArrayList<Long>();
538
        for(Long entityId:entityIdItemMap.keySet()){
539
            boolean isValidEntity = false;
540
            //If any one of the items has been updated before current timestamp, than we generate content for whole entity
541
            for(Item item: entityIdItemMap.get(entityId)){
542
                if(item.getUpdatedOn() > 0){
543
                    isValidEntity = true;
544
                }
545
            }
546
            if(!isValidEntity){
547
                removeEntities.add(entityId);
548
            }
549
        }
550
        for(Long entityId: removeEntities){
551
            entityIdItemMap.remove(entityId);
552
        }
553
    }
5229 varun.gupt 554
 
555
    /**
556
     * Generate XML feed for mobile site
557
     * @throws Exception
558
     */
559
    public void generateXMLFeedForMobileSite() throws Exception	{
560
    	List<String> productXMLSnippets = new ArrayList<String>();
561
		productXMLSnippets.add("<Products>");
562
		List<Long> itemIds = new ArrayList<Long>();
563
 
564
		for(Long entityId: entityIdItemMap.keySet()){
565
			List<Item> items = entityIdItemMap.get(entityId);
566
			Item firstItem = items.get(0);
567
			Utils.info("first Item: " + firstItem);
568
 
569
			if(isMobile(firstItem) || isLaptop(firstItem)) {
570
				itemIds.add(firstItem.getId());
571
			}
572
		}
4188 varun.gupt 573
 
5229 varun.gupt 574
		List<String> descriptions = new ArrayList<String>();
575
		descriptions.add("8MP camera, Super AMOLED Plus display, Android Gingerbread");
576
		descriptions.add("Android OS v2.2 Froyo, 800MHz processor, 3.5\" capacitive display");
577
		descriptions.add("Dual-SIM, Wi-Fi, Bluetooth, Social networking &amp; IM");
578
		descriptions.add("Android Gingerbread, Facebook button, 5MP camera");
579
		descriptions.add("Android Gingerbread, 1GHz processor, 3.7\" Gorilla Glass display");
580
		descriptions.add("2GB RAM, 500GB HDD, Intel Core 2 Duo T6570 processor, DOS");
581
		descriptions.add("4GB RAM, 500GB HDD, Intel Core i5 2410M processor, Windows 7 Basic");
582
		descriptions.add("3.2\" touchscreen, 2MP camera, IM &amp; social networking");
583
 
584
		for(Long entityId: entityIdItemMap.keySet()) {
585
			List<Item> items = entityIdItemMap.get(entityId);
586
			Item firstItem = items.get(0);
587
 
588
			if(!isMobile(firstItem) && !isLaptop(firstItem)){
589
				continue;
590
			}
4188 varun.gupt 591
 
5229 varun.gupt 592
			String url = getProductURL(entityId, firstItem);
593
			String imageUrl = "http://www.saholic.com/images/website" + File.separator + entityId + File.separator + "thumbnail.jpg";
594
			String description = descriptions.get((int) (8 * Math.random()));
595
			double minPrice = getMinPrice(items);
596
 
597
			String productType = "";
598
 
599
			if (firstItem.getCategory() == 10001 || firstItem.getCategory() == 10002 || firstItem.getCategory() == 10003 || firstItem.getCategory() == 10004 || firstItem.getCategory() == 10005)	{
600
				productType = "Mobile Phone";
601
 
602
			} else if (firstItem.getCategory() == 10010)	{
603
				productType = "Tablet";
604
 
605
			} else if (firstItem.getCategory() == 10050)	{
606
				productType = "Laptop";
607
			}
608
 
609
			productXMLSnippets.add(this.xmlIndentation[1] + "<Product>");	
610
 
611
			productXMLSnippets.add(this.xmlIndentation[2] + "<ID>" + entityId + "</ID>");
612
			productXMLSnippets.add(this.xmlIndentation[2] + "<Type>" + productType + "</Type>");
613
			productXMLSnippets.add(this.xmlIndentation[2] + "<Brand>" + firstItem.getBrand() + "</Brand>");
614
			productXMLSnippets.add(this.xmlIndentation[2] + "<ModelName>" + firstItem.getModelName() + "</ModelName>");
615
			productXMLSnippets.add(this.xmlIndentation[2] + "<ModelNumber>" + firstItem.getModelNumber() + "</ModelNumber>");
616
			productXMLSnippets.add(this.xmlIndentation[2] + "<URL>" + url + "</URL>");
617
			productXMLSnippets.add(this.xmlIndentation[2] + "<ImageURL>" + imageUrl + "</ImageURL>");
618
			productXMLSnippets.add(this.xmlIndentation[2] + "<ShortDesc>" + description + "</ShortDesc>");
619
			productXMLSnippets.add(this.xmlIndentation[2] + "<MRP>" + firstItem.getMrp() + "</MRP>");
620
			productXMLSnippets.add(this.xmlIndentation[2] + "<SellingPrice>" + (int)minPrice  + "</SellingPrice>");
621
 
622
			productXMLSnippets.add(this.xmlIndentation[1] + "</Product>");
623
		}
624
 
625
		productXMLSnippets.add("</Products>");
626
 
627
		String productDataXML = StringUtils.join(productXMLSnippets, "\n");
628
 
629
		Utils.info(productDataXML);
630
 
631
		// Write it to file
632
		String productXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "msitedata.xml";
633
		DBUtils.store(productDataXML, productXMLFilename);
634
    }
635
 
4188 varun.gupt 636
	/**
637
	 * Generate the xml list of all the active phones and store in a file
638
	 * @throws Exception
639
	 */
640
	public void generateProductXMLForDisplayAds() throws Exception {
4384 varun.gupt 641
		Utils.info("Generating Product XML for display ads");
4188 varun.gupt 642
		List<String> productXMLSnippets = new ArrayList<String>();
643
		productXMLSnippets.add("<saholic.com>");
644
		List<Long> itemIds = new ArrayList<Long>();
4384 varun.gupt 645
 
646
		Utils.info("Entity Ids: " + entityIdItemMap.keySet());
4188 varun.gupt 647
 
648
		for(Long entityId: entityIdItemMap.keySet()){
649
			List<Item> items = entityIdItemMap.get(entityId);
650
			Item firstItem = items.get(0);
4384 varun.gupt 651
			Utils.info("first Item: " + firstItem);
652
 
4383 varun.gupt 653
			if(isMobile(firstItem) || isLaptop(firstItem)) {
4188 varun.gupt 654
				itemIds.add(firstItem.getId());
655
			}
656
		}
657
 
658
		PromotionClient promotionClient = new PromotionClient();
659
		in.shop2020.model.v1.user.PromotionService.Client promotionServiceClient = promotionClient.getClient();
660
 
661
		List<ItemCouponDiscount> itemsCouponsAndDiscounts = promotionServiceClient.getItemDiscountMap(itemIds);
662
 
663
		Map<Long, ItemCouponDiscount> couponsAndDiscounts = new HashMap<Long, ItemCouponDiscount>();
664
 
665
		for (ItemCouponDiscount itemCouponDiscount: itemsCouponsAndDiscounts) {
666
			couponsAndDiscounts.put(itemCouponDiscount.getItemId(), itemCouponDiscount);
667
		}
4384 varun.gupt 668
		Utils.info("Entity IDs: " + entityIdItemMap.keySet());
4188 varun.gupt 669
 
670
		for(Long entityId: entityIdItemMap.keySet()) {
671
			List<Item> items = entityIdItemMap.get(entityId);
672
			Item firstItem = items.get(0);
4384 varun.gupt 673
 
674
			Utils.info("First Item: " + firstItem);
675
 
4382 varun.gupt 676
			if(!isMobile(firstItem) && !isLaptop(firstItem)){
4188 varun.gupt 677
				continue;
678
			}
679
 
680
			productXMLSnippets.add(this.xmlIndentation[1] + "<products>");	
681
 
682
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
683
 
684
			String title = getProductTitle(firstItem);
685
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + title + "</ProductName>");
686
 
687
			String url = getProductURL(entityId, firstItem);
688
 
689
			String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator + entityId + File.separator + "icon.jpg";    
690
 
691
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + url + "</ProductURL>");
692
 
693
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
694
 
695
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + firstItem.getMrp() + "</ProductMRP>");
696
 
697
			double minPrice = getMinPrice(items);
698
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductSellingPrice>" + (int)minPrice  + "</ProductSellingPrice>");
6602 amit.gupta 699
			productXMLSnippets.add(this.xmlIndentation[2] + "<Availability>" + (inStockCatalogItemIds.contains(entityId) ? "Y" : "N") + "</Availability>");
4188 varun.gupt 700
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductDiscount>" + (int)((firstItem.getMrp()-minPrice)/firstItem.getMrp()*100) + "</ProductDiscount>");
701
 
702
			long itemId = firstItem.getId();
703
 
704
			if(couponsAndDiscounts.containsKey(itemId))	{
705
 
706
				ItemCouponDiscount itemCouponDiscount = couponsAndDiscounts.get(itemId);
707
 
708
				productXMLSnippets.add(this.xmlIndentation[2] + "<ProductCoupons>");
709
				productXMLSnippets.add(this.xmlIndentation[3] + "<Coupon>");
710
				productXMLSnippets.add(this.xmlIndentation[4] + "<CouponCode>" + itemCouponDiscount.getCouponCode() + "</CouponCode>");
711
				productXMLSnippets.add(this.xmlIndentation[4] + "<PriceAfterCoupon>" + (int)(minPrice - itemCouponDiscount.getDiscount()) + "</PriceAfterCoupon>");
712
				productXMLSnippets.add(this.xmlIndentation[3] + "</Coupon>");
713
				productXMLSnippets.add(this.xmlIndentation[2] + "</ProductCoupons>");
714
 
715
			} else	{
716
				productXMLSnippets.add(this.xmlIndentation[2] + "<ProductCoupons />");
717
			}
718
 
719
			String description = "";
720
			Entity entity = CreationUtils.getEntity(entityId);
721
			if(entity!=null){
722
				if(entity.getSlide(130001) !=null){
4202 varun.gupt 723
					description = StringEscapeUtils.escapeXml(entity.getSlide(130001).getFreeformContent().getFreeformText());
4188 varun.gupt 724
				}
725
			}
726
 
727
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductDescription>" + description + "</ProductDescription>");
728
 
729
			productXMLSnippets.add(this.xmlIndentation[1] + "</products>");	
730
		}
731
 
732
		productXMLSnippets.add("</saholic.com>");
733
 
734
		String productDataXML = StringUtils.join(productXMLSnippets, "\n");
735
 
736
		Utils.info(productDataXML);
737
 
738
		// Write it to file
739
		String productXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "advertismentapi.xml";
740
		DBUtils.store(productDataXML, productXMLFilename);
741
	}
5229 varun.gupt 742
 
743
	public static void main(String[] args) throws Exception {
744
		CatalogClient cl = new CatalogClient();
5945 mandeep.dh 745
		in.shop2020.model.v1.catalog.CatalogService.Client client = cl.getClient();
5229 varun.gupt 746
 
5612 amit.gupta 747
//		List<Item> items = cl.getClient().getAllItemsByStatus(status.ACTIVE);
748
		List<Long> items1 = Arrays.asList(1587l,2222l,2258l,2270l,5836l,6718l, 6719l);
749
		List<Item> items = new ArrayList<Item>();
750
		for (Long l : items1) {
751
			items.add(cl.getClient().getItem(l));
752
		}
753
		//items.addAll(cl.getClient().getAllItemsByStatus(status.PAUSED));
5229 varun.gupt 754
//		items.addAll(cl.getClient().getAllItemsByStatus(status.PAUSED_BY_RISK));
755
 
756
		Map<Long, List<Item>> entityIdItemMap1 = new HashMap<Long, List<Item>>();
757
		ProductListGenerator pl = new ProductListGenerator(entityIdItemMap1);
6025 amit.gupta 758
		//pl.generateThinkDigitFeed();
5229 varun.gupt 759
		pl.populateEntityIdItemMap(items);
5612 amit.gupta 760
		//pl.generateAccessoriesXML();
6025 amit.gupta 761
		//pl.generateXMLFeedForMobileSite();
5229 varun.gupt 762
	}
5612 amit.gupta 763
 
764
    private String readFile(String path) throws IOException {
765
		FileInputStream stream = new FileInputStream(new File(path));
766
		try {
767
			FileChannel fc = stream.getChannel();
768
			MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()-1);
769
			/* Instead of using default, pass in a decoder. */
770
			return Charset.defaultCharset().decode(bb).toString();
771
		}
772
		finally {
773
			stream.close();
774
		}
775
	}
6025 amit.gupta 776
    /**
777
     * Feed generated for thinkdigit that only contains the live items
778
     * feed should have s
779
     */
780
    public void generateThinkDigitFeed() throws Exception{
781
 
782
    	List<String> productXMLSnippets = new ArrayList<String>();
783
    	productXMLSnippets.add("<root>");
784
    	String thinkDigitFeedFileName = Utils.EXPORT_PARTNERS_CONTENT_PATH + "all-categories.xml";
785
    	Client catalogClientProd = new CatalogClient(ConfigClientKeys.catalog_service_server_host_prod.toString(), ConfigClientKeys.catalog_service_server_port.toString()).getClient();
6624 rajveer 786
    	for (Long entityId : entityIdItemMap.keySet()){
787
    		List<Item> items = entityIdItemMap.get(entityId);
7373 amit.gupta 788
    		long cate = items.get(0).getCategory();
789
    		Utils.info(cate);
790
    		Category category = Catalog.getInstance().getDefinitionsContainer().getCategory(cate);
791
    		Category parentCategory = category.getParentCategory(); 
6624 rajveer 792
 
793
    		for(Item item: items){
794
    			if(!item.getItemStatus().equals(status.ACTIVE)){
795
    				continue;
796
    			}
797
    			boolean isActive = true;
798
    			if(!inStockCatalogItemIds.contains(entityId)) {
799
    				if(item.isRisky()){
800
	    				try {
801
	    					ItemShippingInfo isi = catalogClientProd.isActive(item.getId());
802
	    					isActive = isi.isIsActive();
803
	    				} catch (Exception e) {
804
	    					Utils.info("Some problem Occurred while fetching shippingInfo for catalogitem " + item.getCatalogItemId() + "\n" +e + "\nTrying again");
805
	    					try {
806
	    					catalogClientProd = new CatalogClient(ConfigClientKeys.catalog_service_server_host_prod.toString(), ConfigClientKeys.catalog_service_server_port.toString()).getClient();
807
	    					ItemShippingInfo isi = catalogClientProd.isActive(item.getId());
808
	    					isActive = isi.isIsActive();
809
	    					} catch (Exception e1) {
810
	    						Utils.info("Some problem in catalog Service for catalog item " +  item.getCatalogItemId()+ " . Marking it true");
811
	        					isActive = true;
812
							}
813
	    				}
6025 amit.gupta 814
    				}
6624 rajveer 815
	    			if(isActive) {
816
		    			inStockCatalogItemIds.add(item.getCatalogItemId());
817
		    			if(validParentCategories.contains(parentCategory.getID())) { 
818
			    			productXMLSnippets.add(this.xmlIndentation[1] + "<products>");
819
			    			productXMLSnippets.add(this.xmlIndentation[2] + "<id>" + item.getCatalogItemId() + "</id>");
820
			    			productXMLSnippets.add(this.xmlIndentation[2] + "<product>" + getProductTitle(item) + "</product>");
821
			    			productXMLSnippets.add(this.xmlIndentation[2] + "<Product_URL>" + getProductURL(item.getCatalogItemId(), item, 59) + "</Product_URL>");
822
			    			productXMLSnippets.add(this.xmlIndentation[2] + "<Product_Price>" + (int)item.getSellingPrice() + "</Product_Price>");
823
			    			productXMLSnippets.add(this.xmlIndentation[2] + "<Merchant_Name>" + "saholic.com" + "</Merchant_Name>");
824
			    			productXMLSnippets.add(this.xmlIndentation[2] + "<Category_Name>" + parentCategory.getLabel() + "</Category_Name>");
825
			    			productXMLSnippets.add(this.xmlIndentation[1] + "</products>");
826
		    			}
6610 amit.gupta 827
	    			}
6025 amit.gupta 828
    			}
829
    		}
830
    	}
831
    	productXMLSnippets.add("</root>");
832
    	String productDataXML = StringUtils.join(productXMLSnippets, "\n");
833
    	DBUtils.store(productDataXML, thinkDigitFeedFileName);
834
 
835
    }
6257 rajveer 836
 
837
    public static void updatePriceForEntity(long catalogItemId, double sp, double mrp){
838
    	try{
839
    		String filename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "saholicmobilephones.xml";
840
    		File file = new File(filename);
841
    		if (file.exists()){
842
    			DOMParser parser = new DOMParser();
843
    			parser.parse(filename);
844
    			Document doc = parser.getDocument();
845
    			NodeList list = doc.getElementsByTagName("ProductSKU");
846
    			for(int i=0; i<list.getLength(); i++){
847
    				if(list.item(i).getTextContent().equals(catalogItemId+"")){
848
    					Node spNode = doc.getElementsByTagName("ProductPrice").item(i);
849
    					spNode.setTextContent(sp+"");
850
    					Node mrpNode = doc.getElementsByTagName("ProductMRP").item(i);
851
    					mrpNode.setTextContent(mrp+"");
852
    				}
853
    			}
854
    			writeXmlFile(doc, filename);
855
    		}
856
    		else{
857
    			System.out.println("File not found!");
858
    		}
859
    	}
860
    	catch (Exception e){
861
    		e.getMessage();
862
    	}
863
    }
864
 
865
    // This method writes a DOM document to a file
866
    public static void writeXmlFile(Document doc, String filename) {
867
    	try {
868
    		// Prepare the DOM document for writing
869
    		Source source = new DOMSource(doc);
870
 
871
    		// Prepare the output file
872
    		File file = new File(filename);
873
    		Result result = new StreamResult(file);
874
 
875
    		// Write the DOM document to the file
876
    		Transformer xformer = TransformerFactory.newInstance().newTransformer();
877
    		xformer.transform(source, result);
878
    	} catch (TransformerConfigurationException e) {
879
    	} catch (TransformerException e) {
880
    	}
881
    }
4143 varun.gupt 882
}