Subversion Repositories SmartDukaan

Rev

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

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