Subversion Repositories SmartDukaan

Rev

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