Subversion Repositories SmartDukaan

Rev

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

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