Subversion Repositories SmartDukaan

Rev

Rev 7629 | Rev 7662 | 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){
7630 amit.gupta 515
    	entityIdItemMap = new HashMap<Long, List<Item>>(); 
4188 varun.gupt 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
    }
5229 varun.gupt 532
 
533
    /**
534
     * Generate XML feed for mobile site
535
     * @throws Exception
536
     */
537
    public void generateXMLFeedForMobileSite() throws Exception	{
538
    	List<String> productXMLSnippets = new ArrayList<String>();
539
		productXMLSnippets.add("<Products>");
540
		List<Long> itemIds = new ArrayList<Long>();
541
 
542
		for(Long entityId: entityIdItemMap.keySet()){
543
			List<Item> items = entityIdItemMap.get(entityId);
544
			Item firstItem = items.get(0);
545
			Utils.info("first Item: " + firstItem);
546
 
547
			if(isMobile(firstItem) || isLaptop(firstItem)) {
548
				itemIds.add(firstItem.getId());
549
			}
550
		}
4188 varun.gupt 551
 
5229 varun.gupt 552
		List<String> descriptions = new ArrayList<String>();
553
		descriptions.add("8MP camera, Super AMOLED Plus display, Android Gingerbread");
554
		descriptions.add("Android OS v2.2 Froyo, 800MHz processor, 3.5\" capacitive display");
555
		descriptions.add("Dual-SIM, Wi-Fi, Bluetooth, Social networking &amp; IM");
556
		descriptions.add("Android Gingerbread, Facebook button, 5MP camera");
557
		descriptions.add("Android Gingerbread, 1GHz processor, 3.7\" Gorilla Glass display");
558
		descriptions.add("2GB RAM, 500GB HDD, Intel Core 2 Duo T6570 processor, DOS");
559
		descriptions.add("4GB RAM, 500GB HDD, Intel Core i5 2410M processor, Windows 7 Basic");
560
		descriptions.add("3.2\" touchscreen, 2MP camera, IM &amp; social networking");
561
 
562
		for(Long entityId: entityIdItemMap.keySet()) {
563
			List<Item> items = entityIdItemMap.get(entityId);
564
			Item firstItem = items.get(0);
565
 
566
			if(!isMobile(firstItem) && !isLaptop(firstItem)){
567
				continue;
568
			}
4188 varun.gupt 569
 
5229 varun.gupt 570
			String url = getProductURL(entityId, firstItem);
571
			String imageUrl = "http://www.saholic.com/images/website" + File.separator + entityId + File.separator + "thumbnail.jpg";
572
			String description = descriptions.get((int) (8 * Math.random()));
573
			double minPrice = getMinPrice(items);
574
 
575
			String productType = "";
576
 
577
			if (firstItem.getCategory() == 10001 || firstItem.getCategory() == 10002 || firstItem.getCategory() == 10003 || firstItem.getCategory() == 10004 || firstItem.getCategory() == 10005)	{
578
				productType = "Mobile Phone";
579
 
580
			} else if (firstItem.getCategory() == 10010)	{
581
				productType = "Tablet";
582
 
583
			} else if (firstItem.getCategory() == 10050)	{
584
				productType = "Laptop";
585
			}
586
 
587
			productXMLSnippets.add(this.xmlIndentation[1] + "<Product>");	
588
 
589
			productXMLSnippets.add(this.xmlIndentation[2] + "<ID>" + entityId + "</ID>");
590
			productXMLSnippets.add(this.xmlIndentation[2] + "<Type>" + productType + "</Type>");
591
			productXMLSnippets.add(this.xmlIndentation[2] + "<Brand>" + firstItem.getBrand() + "</Brand>");
592
			productXMLSnippets.add(this.xmlIndentation[2] + "<ModelName>" + firstItem.getModelName() + "</ModelName>");
593
			productXMLSnippets.add(this.xmlIndentation[2] + "<ModelNumber>" + firstItem.getModelNumber() + "</ModelNumber>");
594
			productXMLSnippets.add(this.xmlIndentation[2] + "<URL>" + url + "</URL>");
595
			productXMLSnippets.add(this.xmlIndentation[2] + "<ImageURL>" + imageUrl + "</ImageURL>");
596
			productXMLSnippets.add(this.xmlIndentation[2] + "<ShortDesc>" + description + "</ShortDesc>");
597
			productXMLSnippets.add(this.xmlIndentation[2] + "<MRP>" + firstItem.getMrp() + "</MRP>");
598
			productXMLSnippets.add(this.xmlIndentation[2] + "<SellingPrice>" + (int)minPrice  + "</SellingPrice>");
599
 
600
			productXMLSnippets.add(this.xmlIndentation[1] + "</Product>");
601
		}
602
 
603
		productXMLSnippets.add("</Products>");
604
 
605
		String productDataXML = StringUtils.join(productXMLSnippets, "\n");
606
 
607
		Utils.info(productDataXML);
608
 
609
		// Write it to file
610
		String productXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "msitedata.xml";
611
		DBUtils.store(productDataXML, productXMLFilename);
612
    }
613
 
4188 varun.gupt 614
	/**
615
	 * Generate the xml list of all the active phones and store in a file
616
	 * @throws Exception
617
	 */
618
	public void generateProductXMLForDisplayAds() throws Exception {
4384 varun.gupt 619
		Utils.info("Generating Product XML for display ads");
4188 varun.gupt 620
		List<String> productXMLSnippets = new ArrayList<String>();
621
		productXMLSnippets.add("<saholic.com>");
622
		List<Long> itemIds = new ArrayList<Long>();
4384 varun.gupt 623
 
624
		Utils.info("Entity Ids: " + entityIdItemMap.keySet());
4188 varun.gupt 625
 
626
		for(Long entityId: entityIdItemMap.keySet()){
627
			List<Item> items = entityIdItemMap.get(entityId);
628
			Item firstItem = items.get(0);
4384 varun.gupt 629
			Utils.info("first Item: " + firstItem);
630
 
4383 varun.gupt 631
			if(isMobile(firstItem) || isLaptop(firstItem)) {
4188 varun.gupt 632
				itemIds.add(firstItem.getId());
633
			}
634
		}
635
 
636
		PromotionClient promotionClient = new PromotionClient();
637
		in.shop2020.model.v1.user.PromotionService.Client promotionServiceClient = promotionClient.getClient();
638
 
639
		List<ItemCouponDiscount> itemsCouponsAndDiscounts = promotionServiceClient.getItemDiscountMap(itemIds);
640
 
641
		Map<Long, ItemCouponDiscount> couponsAndDiscounts = new HashMap<Long, ItemCouponDiscount>();
642
 
643
		for (ItemCouponDiscount itemCouponDiscount: itemsCouponsAndDiscounts) {
644
			couponsAndDiscounts.put(itemCouponDiscount.getItemId(), itemCouponDiscount);
645
		}
4384 varun.gupt 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
 
652
			Utils.info("First Item: " + firstItem);
653
 
4382 varun.gupt 654
			if(!isMobile(firstItem) && !isLaptop(firstItem)){
4188 varun.gupt 655
				continue;
656
			}
657
 
658
			productXMLSnippets.add(this.xmlIndentation[1] + "<products>");	
659
 
660
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
661
 
662
			String title = getProductTitle(firstItem);
663
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + title + "</ProductName>");
664
 
665
			String url = getProductURL(entityId, firstItem);
666
 
667
			String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator + entityId + File.separator + "icon.jpg";    
668
 
669
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + url + "</ProductURL>");
670
 
671
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
672
 
673
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + firstItem.getMrp() + "</ProductMRP>");
674
 
675
			double minPrice = getMinPrice(items);
676
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductSellingPrice>" + (int)minPrice  + "</ProductSellingPrice>");
6602 amit.gupta 677
			productXMLSnippets.add(this.xmlIndentation[2] + "<Availability>" + (inStockCatalogItemIds.contains(entityId) ? "Y" : "N") + "</Availability>");
4188 varun.gupt 678
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductDiscount>" + (int)((firstItem.getMrp()-minPrice)/firstItem.getMrp()*100) + "</ProductDiscount>");
679
 
680
			long itemId = firstItem.getId();
681
 
682
			if(couponsAndDiscounts.containsKey(itemId))	{
683
 
684
				ItemCouponDiscount itemCouponDiscount = couponsAndDiscounts.get(itemId);
685
 
686
				productXMLSnippets.add(this.xmlIndentation[2] + "<ProductCoupons>");
687
				productXMLSnippets.add(this.xmlIndentation[3] + "<Coupon>");
688
				productXMLSnippets.add(this.xmlIndentation[4] + "<CouponCode>" + itemCouponDiscount.getCouponCode() + "</CouponCode>");
689
				productXMLSnippets.add(this.xmlIndentation[4] + "<PriceAfterCoupon>" + (int)(minPrice - itemCouponDiscount.getDiscount()) + "</PriceAfterCoupon>");
690
				productXMLSnippets.add(this.xmlIndentation[3] + "</Coupon>");
691
				productXMLSnippets.add(this.xmlIndentation[2] + "</ProductCoupons>");
692
 
693
			} else	{
694
				productXMLSnippets.add(this.xmlIndentation[2] + "<ProductCoupons />");
695
			}
696
 
697
			String description = "";
698
			Entity entity = CreationUtils.getEntity(entityId);
699
			if(entity!=null){
700
				if(entity.getSlide(130001) !=null){
4202 varun.gupt 701
					description = StringEscapeUtils.escapeXml(entity.getSlide(130001).getFreeformContent().getFreeformText());
4188 varun.gupt 702
				}
703
			}
704
 
705
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductDescription>" + description + "</ProductDescription>");
706
 
707
			productXMLSnippets.add(this.xmlIndentation[1] + "</products>");	
708
		}
709
 
710
		productXMLSnippets.add("</saholic.com>");
711
 
712
		String productDataXML = StringUtils.join(productXMLSnippets, "\n");
713
 
714
		Utils.info(productDataXML);
715
 
716
		// Write it to file
717
		String productXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "advertismentapi.xml";
718
		DBUtils.store(productDataXML, productXMLFilename);
719
	}
5229 varun.gupt 720
 
721
	public static void main(String[] args) throws Exception {
7506 amit.gupta 722
			CatalogClient cl = new CatalogClient();
723
			in.shop2020.model.v1.catalog.CatalogService.Client client = cl.getClient();
7629 amit.gupta 724
			List<Item> items = client.getAllItemsByStatus(status.ACTIVE);
725
			items.addAll(client.getAllItemsByStatus(status.PAUSED));
726
			ProductListGenerator generator = new ProductListGenerator(items);
7506 amit.gupta 727
 
728
        	log.info("Before thinkdigit feed.");
729
        	generator.generateThinkDigitFeed();
5229 varun.gupt 730
 
7506 amit.gupta 731
 
732
    		log.info("Before product list xml.");
733
        	generator.generateProductsListXML();
734
 
735
        	log.info("Before product accessories xml.");
736
        	generator.generateAccessoriesXML();
737
 
738
        	log.info("Before product camera xml.");
739
        	generator.generateCamerasXML();
740
 
741
        	log.info("Before product display ads.");
742
    		//generator.generateProductXMLForDisplayAds();
5229 varun.gupt 743
	}
5612 amit.gupta 744
 
745
    private String readFile(String path) throws IOException {
746
		FileInputStream stream = new FileInputStream(new File(path));
747
		try {
748
			FileChannel fc = stream.getChannel();
749
			MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()-1);
750
			/* Instead of using default, pass in a decoder. */
751
			return Charset.defaultCharset().decode(bb).toString();
752
		}
753
		finally {
754
			stream.close();
755
		}
756
	}
6025 amit.gupta 757
    /**
758
     * Feed generated for thinkdigit that only contains the live items
759
     * feed should have s
760
     */
761
    public void generateThinkDigitFeed() throws Exception{
762
 
763
    	List<String> productXMLSnippets = new ArrayList<String>();
764
    	productXMLSnippets.add("<root>");
765
    	String thinkDigitFeedFileName = Utils.EXPORT_PARTNERS_CONTENT_PATH + "all-categories.xml";
766
    	Client catalogClientProd = new CatalogClient(ConfigClientKeys.catalog_service_server_host_prod.toString(), ConfigClientKeys.catalog_service_server_port.toString()).getClient();
6624 rajveer 767
    	for (Long entityId : entityIdItemMap.keySet()){
768
    		List<Item> items = entityIdItemMap.get(entityId);
7373 amit.gupta 769
    		long cate = items.get(0).getCategory();
7374 amit.gupta 770
 
771
    		Utils.info(items.get(0).getId() + ","  + String.valueOf(cate));
7373 amit.gupta 772
    		Category category = Catalog.getInstance().getDefinitionsContainer().getCategory(cate);
773
    		Category parentCategory = category.getParentCategory(); 
6624 rajveer 774
 
775
    		for(Item item: items){
776
    			if(!item.getItemStatus().equals(status.ACTIVE)){
777
    				continue;
778
    			}
779
    			boolean isActive = true;
780
    			if(!inStockCatalogItemIds.contains(entityId)) {
781
    				if(item.isRisky()){
782
	    				try {
783
	    					ItemShippingInfo isi = catalogClientProd.isActive(item.getId());
784
	    					isActive = isi.isIsActive();
785
	    				} catch (Exception e) {
786
	    					Utils.info("Some problem Occurred while fetching shippingInfo for catalogitem " + item.getCatalogItemId() + "\n" +e + "\nTrying again");
787
	    					try {
788
	    					catalogClientProd = new CatalogClient(ConfigClientKeys.catalog_service_server_host_prod.toString(), ConfigClientKeys.catalog_service_server_port.toString()).getClient();
789
	    					ItemShippingInfo isi = catalogClientProd.isActive(item.getId());
790
	    					isActive = isi.isIsActive();
791
	    					} catch (Exception e1) {
792
	    						Utils.info("Some problem in catalog Service for catalog item " +  item.getCatalogItemId()+ " . Marking it true");
793
	        					isActive = true;
794
							}
795
	    				}
6025 amit.gupta 796
    				}
6624 rajveer 797
	    			if(isActive) {
798
		    			inStockCatalogItemIds.add(item.getCatalogItemId());
799
		    			if(validParentCategories.contains(parentCategory.getID())) { 
800
			    			productXMLSnippets.add(this.xmlIndentation[1] + "<products>");
801
			    			productXMLSnippets.add(this.xmlIndentation[2] + "<id>" + item.getCatalogItemId() + "</id>");
802
			    			productXMLSnippets.add(this.xmlIndentation[2] + "<product>" + getProductTitle(item) + "</product>");
803
			    			productXMLSnippets.add(this.xmlIndentation[2] + "<Product_URL>" + getProductURL(item.getCatalogItemId(), item, 59) + "</Product_URL>");
804
			    			productXMLSnippets.add(this.xmlIndentation[2] + "<Product_Price>" + (int)item.getSellingPrice() + "</Product_Price>");
805
			    			productXMLSnippets.add(this.xmlIndentation[2] + "<Merchant_Name>" + "saholic.com" + "</Merchant_Name>");
806
			    			productXMLSnippets.add(this.xmlIndentation[2] + "<Category_Name>" + parentCategory.getLabel() + "</Category_Name>");
807
			    			productXMLSnippets.add(this.xmlIndentation[1] + "</products>");
808
		    			}
6610 amit.gupta 809
	    			}
6025 amit.gupta 810
    			}
811
    		}
812
    	}
813
    	productXMLSnippets.add("</root>");
814
    	String productDataXML = StringUtils.join(productXMLSnippets, "\n");
815
    	DBUtils.store(productDataXML, thinkDigitFeedFileName);
816
 
817
    }
6257 rajveer 818
 
819
    public static void updatePriceForEntity(long catalogItemId, double sp, double mrp){
820
    	try{
821
    		String filename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "saholicmobilephones.xml";
822
    		File file = new File(filename);
823
    		if (file.exists()){
824
    			DOMParser parser = new DOMParser();
825
    			parser.parse(filename);
826
    			Document doc = parser.getDocument();
827
    			NodeList list = doc.getElementsByTagName("ProductSKU");
828
    			for(int i=0; i<list.getLength(); i++){
829
    				if(list.item(i).getTextContent().equals(catalogItemId+"")){
830
    					Node spNode = doc.getElementsByTagName("ProductPrice").item(i);
831
    					spNode.setTextContent(sp+"");
832
    					Node mrpNode = doc.getElementsByTagName("ProductMRP").item(i);
833
    					mrpNode.setTextContent(mrp+"");
834
    				}
835
    			}
836
    			writeXmlFile(doc, filename);
837
    		}
838
    		else{
839
    			System.out.println("File not found!");
840
    		}
841
    	}
842
    	catch (Exception e){
843
    		e.getMessage();
844
    	}
845
    }
846
 
847
    // This method writes a DOM document to a file
848
    public static void writeXmlFile(Document doc, String filename) {
849
    	try {
850
    		// Prepare the DOM document for writing
851
    		Source source = new DOMSource(doc);
852
 
853
    		// Prepare the output file
854
    		File file = new File(filename);
855
    		Result result = new StreamResult(file);
856
 
857
    		// Write the DOM document to the file
858
    		Transformer xformer = TransformerFactory.newInstance().newTransformer();
859
    		xformer.transform(source, result);
860
    	} catch (TransformerConfigurationException e) {
861
    	} catch (TransformerException e) {
862
    	}
863
    }
4143 varun.gupt 864
}